Java Volatile Race Condition
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
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