Sharing primitives across threads in Java using atomic objects
September 17, 2017 Leave a comment
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.