The more I learn about multithreading, the more complexities on the way. This is a many times discussed topic but none of the articles provided a clear cut conclusion.String is immutable means that you cannot change the value of a string object but you can make your reference point to a new object. But how does this help in thread safety? Below is test class I created to find an answer for this. The output is inconsistent; at times 'java spring' and other 'java spring spring'. Isn't this happening because the code is not thread safe? This is an expected behavior and I know there are ways to rectify the output. But my issue is how does the immutability of String helps in thread safe execution of code?Please explain.
public class Employee {
private String name;
private String skill;
public Employee(String name, String skill) {
this.name = name;
this.skill = skill;
}
public void processEmployee() {
skill = skill +" spring";
System.out.println(skill);
}
}
public class EmployeeRunner {
public static void main(String[] args) {
Employee e1=new Employee("Alice", "java");
Thread t1 = new Thread("t1") {
public void run() {
e1.processEmployee();
}
};
Thread t2 = new Thread("t2") {
public void run() {
e1.processEmployee();
}
};
t1.start();
t2.start();
}
}
Output :
java spring java spring
And sometimes,
java spring java spring spring