Java multi-line thread atomicity and visibility (eight) __java

Source: Internet
Author: User
Tags switches visibility volatile
1. Atomic Sex

Atomicity in Java means that an atomic operation cannot be interrupted by a thread dispatch mechanism; Once the operation has started, it must be executed before the possible context switches (that is, switching to another thread).
But don't think "atomic operations do not require synchronous control (this is wrong)”。
atomicity can be applied to simple operations of basic types except long and double (assignment and return values)。 The 64-bit data types long and double, which are performed within the JVM through two 32-bit operations, are likely to have context switches.If you add the volatile keyword to the long and double variables, you can also get atomicity
but atomicity does not guarantee the correctness of concurrent code.。 For example, in a multiprocessor (possibly single processor but multi-core) multithreaded environment, a thread's write to a variable might simply have the change in the CPU cache, while the access of other threads to the variable is limited to its own CPU cache, causing inconsistencies. Therefore, it is also necessary to use the volatile keyword to ensure visibility, and to write changes to the variables directly into memory.
Of coursethe synchronization (lock) mechanism can also guarantee this visibility, the modification of the variable is written directly into memory.
In the same task, the visibility problem does not exist. That is, the task's modification of the variable, the task must know.
However, when a property's value is dependent on its previous value (such as an increment operation), the value of one property depends on the value of the other domain, and volatile cannot work. Said here can not work, it should mean that in the concurrent environment can not guarantee the correctness of the code.
My understanding:Atomic +volatitle can guarantee the correctness of concurrency。 However, it is best to use synchronous locking to ensure the correctness of concurrent coding. The first option should be the Synchronized keyword.
Again: In Java, the self-add operation is not atomic.
In the fourth edition of "Thinking in Java," the Chinese version of the 682-684 page illustrates the following two points in detail:
(1) In Java, simple operations (assignment, return value) for basic types other than long and double are atomic, but the concurrency is not guaranteed to be correct.
(2) in Java, an incremental operation is not atomic and raises a concurrency problem.2. Atomic Class Atomic

After JDK5, the atoms such as Atomicinteger, Atomiclong and atomicreference are introduced. These classes are actually used to build the classes in the java.util.concurrent. In other words, these classes are the base class for JUC implementations, Juc are built on atomic, and Juc concurrency is implemented with atomic.
When we write code, we should first consider using the Synchronized keyword and lock object, and avoid using the atomic class. When it comes to tuning, you can consider using the atomic class. atomic classes are more efficient than synchronized and lock .
The following uses the atomic class to override Evengenerator:

Package org.fan.learn.thread.share;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import Java.util.concurrent.atomic.AtomicInteger;
/**
 * Created by the ThinkPad on 2016/6/19
 . * * Public
class Atomicevengenerator extends Intgenerator {
    private Atomicinteger Atomicinteger = new Atomicinteger (0);
    @Override public
    int Next () {return
        atomicinteger.addandget (2);
    }
    public static void Main (string[] args) {
        new Timer (). Schedule (new TimerTask () {
            @Override public
            void Run () {
                System.err.println ("aborting");
                System.exit (0);
            }
        }, 5000);  Automatically terminate evenchecker.test after 5s execution
        (new Atomicevengenerator ());
    }

Use timer here to automatically terminate the program after running 5s.
The results of the operation are as follows:
Press Control-c to exit
Aborting

For the rest of Evengenerator, refer to the following two posts:
Java multi-thread access shared resources (vi)
Java multi-thread access shared resources synchronized, lock (vii)

Related Article

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.