开发者

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

开发者 https://www.devze.com 2023-03-07 05:25 出处:网络
This question already has answers here: Do I need to synchronize access to immutable types in Java? 开发者_开发技巧
This question already has answers here: Do I need to synchronize access to immutable types in Java? 开发者_开发技巧 (5 answers) Closed 7 years ago.

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


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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消