Our primary mechanism for managing state in Java is through synchronized methods and blocks. However, there are other options for managing state. Here we’ll look at using the java.util.concurrent.atomic package for atomic counters accessed by multiple threads.
We expect to get exactly 50,000 operations. Had we used a non-atomic long and incremented it with ops++, we’d likely get a different number, changing between runs, because the threads would interfere with each other. Moreover, we’d get data race conditions.
Next we’ll look at locks, another tool for managing state.