Race Conditions

A race condition occurs when two threads attempt to use the same resource at the same time. The following class demonstrates a simple race condition. Two threads simultaneously try to increment a counter. If each thread can complete the increment( ) method in its entirety without the other thread executing, then all is fine, and the counter monotonically increases. Otherwise, the thread context switcher has the opportunity to interrupt one thread in the middle of executing the increment( ) method, and let the other thread run through this method. Note that the thread can actually be interrupted anywhere, not necessarily in the middle of the increment( ) method, but I’ve greatly increased the likelihood of an interruption in the increment( ) method by including a print statement there:

package tuning.threads;

public class ThreadRace
  implements Runnable
{
  //global counter
  static int num=0;

  public static void increment( )
  {
    int n = num;
    //This next line gives the context switcher an ideal
    //place to switch context.
    System.out.print(num+" ");
    //And when it switches back, n will still be the old
    //value from the old thread.
    num = n + 1;
  }

  public static void main(String args[])
  {
    ThreadRace d1 = new ThreadRace( );
    ThreadRace d2 = new ThreadRace( );

    Thread d1Thread = new Thread(d1);
    Thread d2Thread = new Thread(d2);

    d1Thread.start( );
    d2Thread.start( );
  }

  public void run( )
  {
    for (int i = 200; i >= 0 ; i--)
    {
      increment( );
    }
  }
}

The output from executing this class on a ...

Get Java Performance Tuning 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.