As we know that String objects are immutable. It is also true that immutable objects are thread-safe so by transitive law string objects are thread-safe. In this post let’s go a little deeper into this concept of String and thread safety in Java.
For that first let’s define Immutable object and thread safety -
Immutable object - An immutable object is an object that would not be able to change its state after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.
Thread safety– I’ll quote “Java concurrency in practice” book here – A class is thread-safe if it behaves correctly when accessed from multiple threads, where correctness means that a class conforms to its specification.
String, being immutable, has the specification that the Strings are constant; their values cannot be changed after they are created.
But there is a little confusion in many users when it comes to string and thread safety– many people think that string is immutable so thread safety here should mean even if multiple threads are working on the same string those threads should not be able to change the content of the string at all.
But threads can change the content main point here is in that case reference will also change. Whenever content of the String is changed, a new String is created and the reference is changed. Same thing will happen in case of multiple threads too.
Let’s try to see this with an example. In this example three threads are created and all of them share the same string object. In each of these thread, thread name is appended to the string and then that string is printed. Join() method is also used here to wait for all of the threads to finish and then the string object is printed again.
Example Code
public class StrThread implements Runnable {
private String s;
//Constructor
public StrThread(String s){
this.s = s;
}
@Override
public void run() {
System.out.println("in run method " + Thread.currentThread().getName());
try {
// introducing some delay
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
s = s + Thread.currentThread().getName();
System.out.println("String " + s);
}
public static void main(String[] args) {
String str = "abc";
// Three threadss
Thread t1 = new Thread(new StrThread(str));
Thread t2 = new Thread(new StrThread(str));
Thread t3 = new Thread(new StrThread(str));
t1.start();
t2.start();
t3.start();
// Waiting for all of them to finish
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("String is " + str.toString());
}
}
Output
in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-1
String abcThread-2
String abcThread-0
String is abc
Here note that every thread changes the content of the string but in the process where str refers to is also changed, so effectively each of the thread get their own string object. Once all the threads finish, str is printed in the main method again and it can be seen that the original string is printed meaning original reference with the original content remains intact.
To see what may happen with a mutable object let us use StringBuffer in the place of String.
Example code
public class StrThread implements Runnable {
private StringBuffer s;
//Constructor
public StrThread(StringBuffer s){
this.s = s;
}
@Override
public void run() {
System.out.println("in run method " + Thread.currentThread().getName());
try {
// introducing some delay
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.append(Thread.currentThread().getName());
System.out.println("String " + s);
}
public static void main(String[] args) {
StringBuffer str = new StringBuffer("abc");
// Three threadss
Thread t1 = new Thread(new StrThread(str));
Thread t2 = new Thread(new StrThread(str));
Thread t3 = new Thread(new StrThread(str));
t1.start();
t2.start();
t3.start();
// Waiting for all of them to finish
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("String is " + str.toString());
}
}
Output
in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-0
String abcThread-0Thread-2
String abcThread-0Thread-2Thread-1
String is abcThread-0Thread-2Thread-1
Note – output may vary in different runs
Here it can be seen that shared StringBuffer object is modified.
That's all for this topic String and thread-safety in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related topics
You may also like -