Race conditions

Let's start by looking at some concurrency bugs. Here is a simple example of incrementing a counter:

public class Counter {  private int counter;      public int incrementAndGet() {    ++counter;    return counter;}

This code is not thread-safe. If two threads are running using the same object concurrently, the sequence of counter values each gets is essentially unpredictable.  The reason for this is the ++counter operation. This simple-looking statement is actually made up of three distinct operations, namely read the new value,  modify the new value, and store the new value:

         

As shown in the preceding diagram, the thread executions ...

Get Concurrent Patterns and Best Practices now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.