-1

While reading about strings I came to know that strings are thread safe I want a example demonstrating the scenario.

  • 6
    `String`s are immutable -> they are thead safe. – Amongalen Aug 23 '19 at 08:26
  • StackOverflow is not a code-writing service. Please read through the [Help Center](https://stackoverflow.com/help), in particular [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Andreas Aug 23 '19 at 08:48

2 Answers2

2

When we say something as thread safe, it means more than one thread trying to access a resource will not lead to any sort of inconsistency. We know that every thread has shared access to all the objects stored in the heap memory. One more thing to be noted is that all object references assignments are atomic operations, which means all object reference assignments are thread safe. Because any atomic operation is just one operation and will be completed entirely whenever CPU is assigned to it. Having said that, now string itself are immutable. Meaning, you cannot change the value inside the string object present in heap. So if it is read by any thread, it will always be of same value. So, no inconsistency. Also, when you try to assign s1 = s2, then it is just creating a new reference called s1 and so it is just an object reference assignment statement which is atomic. Hence, strings are thread safe. Same argument holds for any immutable objects.

As an extra clarification, I would go ahead and explain what happens with long and double datatypes. Assignment operations to long and double are not atomic as it take more than one operation to complete the assignment (if 64 bit required, so first cycle, 32 bits are copied, second cycle, 32 bits are copied). But if you mark the assignment as volatile, then JVM takes care of this and completes the entire assignment in one operation. So long and double with volatile keyword also becomes thread safe.

Navin Gelot
  • 1,264
  • 3
  • 13
  • 32
Deep
  • 76
  • 6
0

String is a value object and once instantiated its value could not be changed. Hence it is thread safe after its construction, multiple concurrent access could only read from its value.

Awan Biru
  • 373
  • 2
  • 10