Skip to content

Instantly share code, notes, and snippets.

@NicMcPhee
Last active October 25, 2024 08:48
Show Gist options
  • Save NicMcPhee/7567337 to your computer and use it in GitHub Desktop.
Save NicMcPhee/7567337 to your computer and use it in GitHub Desktop.
A simple example of a successful use of Java synchronization to eliminate race conditions. The "synchronized" keyword on Counter.incrementCount() is crucial here; removing it will lead to serious race conditions on multiple-core computers. Having it ensures that two threads can't enter this method at the same time, making sure that only one thre…
public class Counter {
private int count = 0;
public int getCount() {
return count ;
}
/**
* The "synchronized" keyword is crucial here; removing it will lead to serious
* race conditions on multiple-core computers. Having it ensures that two threads
* can't enter this method at the same time, making sure that only one thread passes
* through this method at a time, which ensures that the increments are handled
* correctly.
*/
public synchronized void incrementCount() {
++count;
}
}
public class SynchronizedIncrement implements Runnable {
private static final int NUM_THREADS = 4;
private static final int NUM_INCREMENTS = 10000;
private Counter counter;
public SynchronizedIncrement(Counter counter) {
this.counter = counter;
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[NUM_THREADS];
Counter counter = new Counter();
for (int i=0; i<NUM_THREADS; ++i) {
threads[i] = new Thread(new SynchronizedIncrement(counter));
threads[i].start();
}
for (int i=0; i<NUM_THREADS; ++i) {
threads[i].join();
}
System.out.println("total count = " + counter.getCount() + " vs. expected = " + (NUM_THREADS * NUM_INCREMENTS));
}
@Override
public void run() {
for (int i=0; i<NUM_INCREMENTS; ++i) {
counter.incrementCount();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment