Understanding the pitfalls in java-18.4 java multi-thread atomic operations

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.