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".

  • four
    What caching, you do not wait while at you streams will fulfill to the end. Use unsafe StringBuilder in multithreading. In addition, it may well be a local variable in the main method. - Mage
  • I think you forgot about synchronized - andreich
  • one
    > Volatile does not work 20 years of work on java is ashes - a brilliant Russian programmer found a critical bug in the language - DreamChild
  • ))) I mean that it does not work for me)) - romashechka
  • one
    C'mon you, zaminusovali for nothing. - etki

1 answer 1

@romashechka , the fact that you declared a static field sb volatile will affect only it, and not the internal state of the StringBuilder object.

If you made multiple assignments of the form sb=... , then the volatile would ensure the visibility of these assignments between threads. But you call sb.append(...) , changing the internal state of the object. And StringBuilder , as you noticed @Mage , does not implement thread safety for its internal state. So what needs to be done is synchronized .

  • one
    Well, since this is not your first question on multithreading, I traditionally recommend a "book with a train." The author meticulously chews all the nuances of working with threads. ! BrianGoetz - Nofate
  • here I also read the inquiring volatile ibm.com/developerworks/java/library/j-jtp06197/index.html - romashechka