Is String get/set threadsafe?

妖精的绣舞 提交于 2019-12-09 15:59:08

问题


Let's say I have the following,

public class Foo{
    private String bar;

    public String getBar(){
        return bar;
    }

    public void setBar(String bar){
        this.bar = bar;
    }
}

Are these methods automatically threadsafe due to the immutable nature of the String class, or is some locking mechanism required?


回答1:


No, this is not threadsafe. Foo is mutable, so if you want to ensure that different threads see the same value of bar – that is, consistency – either:

  • Make bar volatile, or
  • Make the methods synchronized, or
  • Use an AtomicReference<String>.

The reads and writes of bar are themselves atomic, but atomicity is not thread safety.

http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html


For in-depth coverage of Java concurrency, grab a copy of Java Concurrency in Practice (aka JCIP).




回答2:


You're setting references, and as such String's immutability doesn't come into play. You're not affecting the contents of String.




回答3:


No, not safe.

This is Foo mutable behavior; String's immutability does not accrue to Foo.

public class Foo{
    private String bar;

    public synchronized String getBar(){
        return bar;
    }

    public synchronized void setBar(String bar){
        this.bar = bar;
    }
}



回答4:


No, it's not thread safe.

While String is immutable, the issue comes from the field of Foo. To make this more apparent, consider for example a method whose job would be to append (rather than replace) the value of bar. When it's called from multiple threads, some writes could be lost. The same (lost writes) can happen with your simple setter too, even if it's not obvious initially in this case.



来源:https://stackoverflow.com/questions/15072578/is-string-get-set-threadsafe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!