O'Reilly logo

Concurrent Patterns and Best Practices by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required