Understanding the pitfalls in java-18.4 java multi-thread atomic operations
In this chapter, we will discuss the pitfalls in java multithreading atomicity.
1. Seemingly atomic operations:
Package com. ray. ch18; public class Test {private int a = 0; private int B = 0; public void methodA () {B = a + 1;} public int methodB () {return ;}}
Observe the above Code. The two methods seem to be atomic operations.
2. Uncover the true face of the above Code (decompiling through javap ):
It is the virtual code after decompilation. Let's look at two red boxes. In methodA, although there is only one sentence B = a + 1, there are two sentences of code in the jvm execution process, one is get and the other is put. If it is a multi-threaded operation, the code in the middle may be read or written by other threads. Therefore, this operation is not an atomic operation.
3. Conclusion:
In multi-threaded programming, do not rely on atomic operations (unless you are experts). We recommend that you use synchronized to ensure the atomicity of operations.
4. General Atomic operations include:
Assignment and return
Code:
Package com. ray. ch18; public class Test {private int a = 0; private int B = 0; public void methodA () {B = 1 ;}public int methodB () {return ;}}
Decompilation:
There is only one sentence in the red box, and there is no other code in the middle.
Summary: This chapter illustrates the pitfalls in multi-threaded atomic operations.
This chapter is here. Thank you.