Skip to content

Instantly share code, notes, and snippets.

@NicMcPhee
Created November 20, 2013 16:42
Show Gist options
  • Save NicMcPhee/7566471 to your computer and use it in GitHub Desktop.
Save NicMcPhee/7566471 to your computer and use it in GitHub Desktop.
A simple example that illustrates the existence of race conditions when using Java Threads. If you run this code on a multi-core box you're likely to get a lower count (potentially much lower) than you might naively expect.
public class SimpleIncrement implements Runnable {
private static final int NUM_THREADS = 4;
private static final int NUM_INCREMENTS = 10000;
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[NUM_THREADS];
for (int i=0; i<NUM_THREADS; ++i) {
threads[i] = new Thread(new SimpleIncrement());
threads[i].start();
}
for (int i=0; i<NUM_THREADS; ++i) {
threads[i].join();
}
System.out.println("total count = " + count + " vs. expected = " + (NUM_THREADS * NUM_INCREMENTS));
}
@Override
public void run() {
for (int i=0; i<NUM_INCREMENTS; ++i) {
++count;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment