Java provides built-in support for atomic operations through the java.util.concurrent.atomic package. We’ll use this package to create an atomic counter that can be safely 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.
To run the program:
Next, we’ll look at locks, another tool for managing state in concurrent programs.