Java assignment issues - Is this atomic?

前端 未结 4 1697
刺人心
刺人心 2021-02-14 22:01

I\'ve got some questions about Java\'s assigment.

  • Strings

I\'ve got a class:

public class Test {
 private String s;

 public synchro         


        
4条回答
  •  我在风中等你
    2021-02-14 22:41

    Earlier answers are correct in pointing that with new (1.5+) JVMs, String version is safe, with respect to data corruption. And you seem to be aware of downside non-synchronized access; that of changes not necessarily being visible via getters.

    However: more useful question is this: is there reason to synchronization here? If this is just for being interested in knowing this, that's all good. But for real code, the general rule of reads and writes is that if there can be both, both should be synchronized. So although you can in this case leave out synchronization (potentially meaning that threads do not see changes other threads make), there seems to be little benefit in doing that.

提交回复
热议问题