Skip to content

Instantly share code, notes, and snippets.

@markon

markon/VolatileRaceCondition.java Secret

Last active Nov 3, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.