/** * A simple program to demonstrate data races * * Author: John C. Linford (jlinford@vt.edu) * Date: 25 August 2005 * License: Public Domain */ public class DataRace { private int[] shared = new int[1]; private Thread t1, t2; public DataRace() { // // Create a first thread to increment shared // t1 = new Thread() { public void run() { int copy = 0; // Stores a copy of shared to detect races while(t1 != null) { // Make a copy of shared in a safe way synchronized(shared) { copy = shared[0]; } // Increment shared unsafely (possible race) shared[0] = shared[0] + 1; // Check for a race condition in a safe way synchronized(shared) { System.out.println("[t1] -- Shared: " + shared[0] + "."); if(shared[0] - 1 != copy) { System.err.println("[t1] -- Data Race! Had " + shared[0] + " when I expected " + (copy + 1) + "."); t1 = t2 = null; } } } } }; // // Create a second thread to increment shared // t2 = new Thread() { public void run() { int copy = 0; // Stores a copy of shared to detect races while(t2 != null) { // Make a copy of shared in a safe way synchronized(shared) { copy = shared[0]; } // Increment shared unsafely (possible race) shared[0] = shared[0] + 1; // Check for a race condition in a safe way synchronized(shared) { System.out.println("[t2] -- Shared: " + shared[0] + "."); if(shared[0] - 1 != copy) { System.err.println("[t2] -- Data Race! Had " + shared[0] + " when I expected " + (copy + 1) + "."); t1 = t2 = null; } } } } }; t1.start(); t2.start(); } public static void main(String[] args) { new DataRace(); } }