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 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.