Skip to content

Instantly share code, notes, and snippets.

@calvinnor
Last active October 2, 2019 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvinnor/b199a8ab9c8f82cb978ecede92c677d0 to your computer and use it in GitHub Desktop.
Save calvinnor/b199a8ab9c8f82cb978ecede92c677d0 to your computer and use it in GitHub Desktop.
A Java Execution manipulating a shared variable, with Synchronisation
public class WithSync {
private static final int NUM_EXECUTIONS = 100000000;
// This Object ensures synchronization
private static final Object mutexLock = new Object();
private static void someLongOperation() { /* NO-OP */ }
public static void main(String[] args) {
final long[] numElements = {0};
Thread incrementThread = new Thread() {
@Override
public void run() {
for (long count = 0; count < NUM_EXECUTIONS; count++) {
someLongOperation();
synchronized(mutexLock) {
numElements[0] += 1;
}
}
}
};
Thread decrementThread = new Thread() {
@Override
public void run() {
for (long count = 0; count < NUM_EXECUTIONS; count++) {
someLongOperation();
synchronized(mutexLock) {
numElements[0] -= 1;
}
}
}
};
// Start the threads
incrementThread.start(); decrementThread.start();
// Wait for jobs to finish
try { incrementThread.join(); decrementThread.join(); }
catch (InterruptedException e) { /* NO-OP */ }
// Print the result
System.out.println("Result is: " + numElements[0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment