Shane
Shane

Reputation: 2351

Sharing data without synchronization - is this code thread safe?

I found this code on Peter Lawry's blog here. He mentions that this class doesn't require any further synchronization.

I am trying to improve my knowledge of concurrency and how to avoid unnecessary synchronization so am trying to figure how to reason about this case from a java memory model point of view.

The reference to the string array is final and the string themselves are immutable but the references to the strings contained in the array are mutable

Upvotes: 2

Views: 125

Answers (2)

user4774371
user4774371

Reputation:

I agree with Sorontur comment about visibility. This code can produce unexpected results (it can be tricky to reproduce scenario). It seems intern method is not thread safe. Multiple threads can run in parallel on multiple cores, usually each core has its own cache. If one thread update any variable in intern, it will immediately update its cache but cache of other core will not update at same time, will take sometime, meanwhile other threads may use old values. So, to carter this situation you can use volatile variables but it will effect performance. Hence, multi-threading on shared memory model is a trade-off between performance and efficiency.

Note: I think unexpected behavior can be seen on concurrent threads, it is not specific to parallel execution

Upvotes: 0

Sorontur
Sorontur

Reputation: 510

In your case I think that we don't care that the String is interned twice. The memory model takes care that nothing evil happens when assigning array values. Here is a related question: java array thread-safety

From the concurrency point of view it is working without synchronisation because the data is safe. So the class is working correctly in concurrent access.

If you like to be strict in the case that intern should happen only once you need to have synchronisation but that has its price. It depends on your use case what correctness is for you. (as pointed by gudok: independent of concurrency still intern happens more than once because of hashing)

Upvotes: 2

Related Questions