我们知道不变对象是指一旦创建不能修改内部状态的对象,因为不变对象没有提供可供修改内部状态的方法,所以不变对象是线程安全的。但是String,当然包括其他的基本数据的包装类,如Integer/Long/Float等等,也是不变对象,但却是可以修改值的,这怎么保证线程安全?
public class Test{
private String str;
public void test(){
if(("").equals(str)){ //多个线程同时判断,可能导致多次执行
str = "1";
//do something
}
}
}
Find another object that can be locked, lock it and then modify the String.
In Java, String type objects themselves are immutable. Because String will be stored in a memory area called the constant pool.
For example
Output:
So why do you feel variable again?
Then a becomes test1. In fact, a new "test1" string object is created here (if the constant pool does not have this value, it is newly created). Then point the variable reference to it. Note: The internal state of the "test" variable is not modified here. The "test" string object is thread-safe.
Unless you modify it with final, all variables pointed to are mutable.
Thread safety must be ensured in this case:
No. 0: You can consider using volatile to ensure visibility.
First, you can use final modification
Second, you can use atomic objects such as AtomicReference, and for Integer, there are also AtomicInteger and the like
Third, lock the corresponding code area