Created
November 20, 2013 17:24
-
-
Save NicMcPhee/7567240 to your computer and use it in GitHub Desktop.
An simple example of an *incorrect* use of Java synchronization. Synchronizing the incrementCount() method doesn't actually fix the race condition because synchronization happens on a per *object* basis and we have multiple separate objects, each running in a separate thread, so the synchronization really accomplishes nothing here.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IncorrectSynchronizedIncrement 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 IncorrectSynchronizedIncrement()); | |
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) { | |
incrementCount(); | |
} | |
} | |
/** | |
* This doesn't actually fix the problem because synchronization happens on a per *object* | |
* basis and we have multiple separate objects, each running in a separate thread, so the | |
* synchronization really accomplishes nothing here. | |
*/ | |
private synchronized void incrementCount() { | |
++count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment