Last active
October 2, 2019 07:25
-
-
Save calvinnor/7ba68023c7b27bd21f7e8e664b2863c2 to your computer and use it in GitHub Desktop.
A Java Execution manipulating a shared variable, without Synchronisation
This file contains 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 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