Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How String class is thread safe in java?

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?

like image 382
Suresh Kb Avatar asked Jan 06 '23 00:01

Suresh Kb


1 Answers

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.

like image 61
Mureinik Avatar answered Jan 08 '23 15:01

Mureinik