Skip to content

Instantly share code, notes, and snippets.

@markon
Last active November 3, 2018 15:11
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 markon/7183881d1cb81cda44554f694884438e to your computer and use it in GitHub Desktop.
Save markon/7183881d1cb81cda44554f694884438e to your computer and use it in GitHub Desktop.
Java Volatile Race Condition
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.ArrayList;
public class VolatileRaceCondition {
private static final int NTHREADS = 10;
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
for (int i = 0; i < 100; i++) {
Runnable worker = new MyRunnable(i);
executor.execute(worker);
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
executor.awaitTermination(60, TimeUnit.SECONDS);
System.out.println("Finished all threads");
for(Integer i: WithGlobalVariable.nums) {
System.out.println(i);
}
}
private static class WithGlobalVariable {
public static volatile List<Integer> nums = new ArrayList<Integer>();
}
private static class MyRunnable implements Runnable {
private final int countUntil;
MyRunnable(int countUntil) {
this.countUntil = countUntil;
}
@Override
public void run() {
WithGlobalVariable.nums.add(this.countUntil);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment