package com.whirlycott.samples; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * How much of a difference does the volatile keyword make? * * Public domain. * * @author pjacob * */ public class VolatileTest { //A normal long. private static long normalCount = 0; //A volatile long. private static volatile long volatileCount = 0; //Number loops to use. private static final long LOOP_COUNT = 10 * 1000 * 1000; //How many threads should we use? private static final long THREAD_COUNT = 32; public static void main(String[] args) throws InterruptedException { final List threads = new ArrayList(); for (int n=0; n < THREAD_COUNT; n++) { //Make a little anonymous thread. final Thread t = new Thread("Thread: " + n) { public void run() { for (long i = 0; i < LOOP_COUNT; i++) { normalCount++; volatileCount++; } } }; //Add the threads to a List so we can wait for them (need a ref to do this) threads.add(t); //Start up the thread t.start(); } System.out.println("All threads started."); //Now, wait for the threads to complete for (final Iterator i = threads.iterator(); i.hasNext(); ) { final Thread t = (Thread)i.next(); t.join(); } System.out.println("Number of loops: " + ( THREAD_COUNT * LOOP_COUNT)); System.out.println("Non-volatile long: " + normalCount); System.out.println("Volatile long: " + volatileCount); } }