public class Tester{ static volatile StringBuilder sb = new StringBuilder(""); public static void main(String[] args) throws Exception, Throwable { Tester t = new Tester(); ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { es.execute(new Runnable(){ @Override public void run() { sb.append("a"); } }); } es.shutdown(); System.out.println(sb); } }
If volatile should disable caching, why do I see different results after each program launch?
That "aaa", then "aaaaa", then "aaaa" or even "aaa a".