Thread safety of JAVA assignment statements, such as int a = 1 thread safety?

Thread safety of assignment statements in java
is int a = 1 thread safe? Is
int b = 2;
a = b thread safe?

Object c = new Object () is thread safe?

the answer I found in my blog is that the first thread is safe, the second doesn"t know, and the third thread is not safe.

here are some explanations I found:
int I = 1;
is thread-safe because this statement will be translated into an instruction iconst_1, there is no thread-safety problem;

/ / A c = new A ();
this operation is divided into three parts
1. Create a symbolic reference to an in the stack
2. Create an An object in the heap
3. Point a to A
, so this assignment statement is not thread-safe

.

does not see any shared objects in the problem, what about thread safety and not?


  1. variables defined within the method do not have thread safety issues;
  2. Objects created inside the
  3. method do not have thread safety issues as long as they are not accessed by other threads.

how to achieve thread safety, in fact, as long as you deal with thread safety when writing a class, you don't have to worry about using this class. If a class is known to be thread-unsafe (such as StringBuilder), then limit its use to the current method.

Menu