In Java, does read only access to Strings need to be synchronized? [duplicate]

烈酒焚心 提交于 2019-12-22 12:19:41

问题


Is it required to synchronize read only access to Strings in Java?


回答1:


No. Strings are immutable. If all you're doing is reading the String, you're absolutely fine.

Edit to add: Yes, if you have a mutable property, that changing the value of the property would need to be synchronized.




回答2:


Immutable objects like String are thread safe, in that their internal state will never change, and final references to those String objects are thread safe.

But, if you have a non-final reference to an immutable object, it isn't completely thread safe.

Given :

public final String x = "This reference is thread safe, it can never change";

any references to x are thread safe since what x refers to can never change and the String object is immutable.

And given :

public String s = "This reference is not thread safe, it can change";

any references to s are not thread safe, because s can possibly change to something else. That is :

s = "this is another different immutable String";

can change what s refers to. If your references should never change make them final if they are expected to change you should declare them volatile so the JVM knows to re-read the contents of the reference and not do any caching optomizations that might miss changes to s.

public volatile String s = "This reference is expected to change, so tell the JVM";

See The final word on final for more information on thread safety and the final keyword.




回答3:


Not for a String, per se, but for the reference to a String, definitely.

Edit:

The references of variables that are not declared as final (or otherwise synchronized) are not guaranteed to be seen by all threads. While it is safe for many threads to read the value of the same String object, you need to somehow guarantee that all threads are reading the most up to date reference.




回答4:


Strings are immutable objects and therefore thread-safe in themselves. Note that a function like String.toUpperCase() does not change the String object itself but returns a new String.

StringBuffer and StringBuilder are mutable objects. StringBuffer is thread-safe and StringBuilder is not.




回答5:


Every String access is read only (Strings are immutable) and because the content of a String instance can't change, there's no need to synchronize.



来源:https://stackoverflow.com/questions/6060129/in-java-does-read-only-access-to-strings-need-to-be-synchronized

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