5
public class ThreadString extends Thread {
    String str = "ABC";

    public void run() {
        str = "abc";
    }
}

if threads are accessing above run method, reference to the "ABC" now pointing to "abc" how it will works internally?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Suresh Kb
  • 151
  • 1
  • 8
  • 2
    `String` is immutable. All you are doing is modifying a reference. – Elliott Frisch May 28 '16 at 18:40
  • This class is not thread-safe. – Andy Turner May 28 '16 at 18:41
  • 3
    Well, you're title asks something different, than your text. If you want to get an answer for your question in the title, read [this](http://stackoverflow.com/questions/9303532/immutable-objects-are-thread-safe-but-why) or [that](http://stackoverflow.com/questions/25224033/does-immutability-guarantee-thread-safety). – Tom May 28 '16 at 18:43
  • 2
    @AndyTurner, If that's the complete definition of `ThreadString`, then what's not "thread-safe" about it? "thread-safe" doesn't mean there's no thread-unsafe way to _use_ the class. There are thread-unsafe ways to use _any_ class. Thread-safe only means that overlapped access from multiple threads won't make any of the methods violate their API contract or put any of the class's data into a bad state. There are no obvious invalid states for the `ThreadString` class's data, and the class's only method just performs a single, atomic operation. – Solomon Slow May 28 '16 at 19:45
  • 1
    The immutable class in itself is thread safe but reference of immutable class is not thread safe. You are using a String reference in your class. – bpjoshi Oct 27 '17 at 09:28

1 Answers1

10

Strings in Java are immutable. You aren't modifying the String, you're just pointing to another value. From that point of view, it's thread safe - str is either "ABC" or "abc", it can't be something invalid or illegal.

Mureinik
  • 297,002
  • 52
  • 306
  • 350