Sharing primitives across threads in Java using atomic objects

Threading and parallel execution are popular choices when making applications more responsive and resource-efficient. Various tasks are carried out on separate threads where they either produce some result relevant to the main thread or just run in the background “unnoticed”. Often these tasks work autonomously meaning they have their own set of dependencies and variables. That is they do not interfere with a resource that is common to 2 or more threads.

However, that’s not always the case. Imagine that multiple threads are trying to update the same primitive like an integer counter. They perform some action and then update this counter. In this post we’ll see what can go wrong.

Read more of this post

Advertisement

Getting the result of the first completed parallel task in Java

In this post we saw how to delegate one or more parallel tasks to different threads and wait for all of them to complete. We pretended that 4 different computations took 1,2,3 and respectively 4 seconds to complete. If we execute each calculation one after the other on the same thread then it takes 10 seconds to complete them all. We can do a lot better by assigning each operation to a separate thread and let them run in parallel. The Future and Callable of T objects along with a thread pool make this very easy to implement.

There are situations where we only need the result from 1 parallel operation. Imagine that it’s enough to complete 1 of the four computations in the example code so that our main thread can continue. We don’t know how long each operation will take so we let them have a race. The one that is executed first returns its value and the rest are interrupted and forgotten. We’ll see how to achieve that in this post.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: