Things to consider when writing thread-safe code:
1. Shared variables
2. Mutable variables
Shared means that multiple threads can access it at the same time, and mutable means that its value can change during its life cycle.
For example, the following count variable:
Copy the code code as follows:
//Thread-unsafe class
public class UnsafeCount {
private int count = 0; //This variable is shared
public void increase() { //There is no synchronization mechanism here, multiple threads can access at the same time
count++; //This variable is variable
}
public int getCount() {
return count;
}
}
There are 4 ways to fix this problem:
1. Instead of sharing the state variable among threads, you can encapsulate the variable into a method (stateless objects must be thread-safe); because the variables in the method are exclusive to each thread and are not shared with other threads. for example:
Copy the code code as follows:
public int add(int count){
return ++count;//It can also be said here that stateless objects must be thread-safe
}
2. Modify the state variable to an immutable variable.
Copy the code code as follows:
private final int count = 0;
3. Use synchronization strategy when accessing state variables.
Copy the code code as follows:
public synchronized void increase() {
count++;
}
4. Use atomic variable classes.
Copy the code code as follows:
private AtomicInteger count;
public void increase() {
count.getAndAdd(1);
}