Skip to content

Instantly share code, notes, and snippets.

Last active November 3, 2018 15:11
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);
// This will make the executor accept no new threads
// and finish all existing threads in the queue
// Wait until all threads are finish
executor.awaitTermination(60, TimeUnit.SECONDS);
System.out.println("Finished all threads");
for(Integer i: WithGlobalVariable.nums) {
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;
public void run() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment