Ensure Atomicity

The previous example had no explicit synchronization in code, but any related euphoria is short-lived. We can’t avoid synchronization if our mutable state has more than one related or dependent variable and we use the JDK concurrency API. Let’s see how.

Our success with the refactoring efforts so far did not go unnoticed. We’ve now been asked to make an enhancement: to keep track of the energy source’s usage. Each time the energy source is drained, we need to keep a count. This means we need to ensure that the changes to level and to the new variable usage are atomic. In other words, changes to both of them in a thread should be kept or both of them discarded. We should never be able to see change to one of the fields and not ...

Get Programming Concurrency on the JVM now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.