Skip to content

Instantly share code, notes, and snippets.

@calvinnor
Last active October 2, 2019 07:25
Show Gist options
  • Save calvinnor/7ba68023c7b27bd21f7e8e664b2863c2 to your computer and use it in GitHub Desktop.
Save calvinnor/7ba68023c7b27bd21f7e8e664b2863c2 to your computer and use it in GitHub Desktop.
A Java Execution manipulating a shared variable, without Synchronisation
public class WithoutSync {
private static final int NUM_EXECUTIONS = 100000000;
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();
numElements[0] += 1;
}
}
};
Thread decrementThread = new Thread() {
@Override
public void run() {
for (long count = 0; count < NUM_EXECUTIONS; count++) {
someLongOperation();
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