Are member variables and static variables thread safe?
- If there is no sharing, then thread-safe
- If they are shared, according to whether their status can be changed, there are two cases
- If there are only read operations, thread-safe
- If there are read and write operations, this code is a critical section, and thread safety needs to be considered
Are local variables thread safe?
- Local variables are thread safe
- But the objects referenced by local variables may not
- If the object is not accessed from the role of escape method, it is thread-safe
- If the object escapes the scope of the method, you need to consider thread safety
Local variable thread safety analysis:
public static void test1(){
int i=10;
i++;
}
When each thread calls the test1() method, the local variable i will be created in the stack frame memory of each thread, so there is no sharing
The reference of local variables is slightly different: if the scope of the reference is within the method and the referenced object is not exposed to the outside, then it is thread-safe, but if it is exposed to the outside, then thread safety issues need to be considered
Common thread safety classes
String, Integer, StringBuffer, Random, Vector, Hashtable, classes under the java.util.concurrent package
It is said that they are thread-safe here means that when multiple threads call their methods of the same instance, they are thread-safe, which can also be understood as:
- Each of their methods is atomic
- But note that the combination of their multiple methods is not atomic
Immutable class thread safety
- String, Integer, etc. are immutable, because their internal state cannot be changed, so their methods are thread-safe
- Protected copy