Using a volatile variable or an atomic variable

Source: Internet
Author: User
Tags variables thread volatile

Volatile variable

In the Java language, volatile variables provide a lightweight synchronization mechanism in which volatile variables are used to ensure that updates to a variable are notified to other threads, and that volatile variables are not cached to registers or to places that are not visible to other processors. Therefore, when reading the volatile variable, it always returns the most recently written value, and the volatile variable is usually used to represent a state identity.

Atomic variables:

The atomic variable is the "more powerful volatile" variable, from the implementation point of view, the Value property of each atomic variable class is a volatile variable, so the characteristic atomic variable of volatile variable also has. At the same time, atomic variables provide read, modify, write atomic operations, more powerful, more in line with the requirements of the general concurrent scenarios.

Since atomic variables are more powerful, is it necessary to use volatile variables? If there is a time to choose the volatile variable, when to select the atomic variable? Of course, this choice only in the context of multithreaded concurrency will appear, and the purpose of multithreading concurrency is generally to improve throughput and reduce latency response, so it is better to look at the paragraph test code and run the results!

Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.atomic.AtomicInteger;
    public class Testvolatile {private static int calc_time = 1000;
    private static final int thread_num = 100;
    Private Atomicinteger AI;
    private int i;
                                                                                                                                                                                                               
    private volatile int VI;  Public
        Testvolatile () {ai = new Atomicinteger (0);
        i = 0;
    VI = 0;  public static void Main (string[] args) throws Interruptedexception {System.out.println ("Calculation times:"
        + Calc_time + "----------------------");
                                                                                                                                                                                                                   
        Test (); Calc_Time = 10000;
        SYSTEM.OUT.PRINTLN ("Calculation times:" + calc_time + "----------------------");
                                                                                                                                                                                                                   
        Test (); Calc_time = 100
        000;
        SYSTEM.OUT.PRINTLN ("Calculation times:" + calc_time + "----------------------");
                                                                                                                                                                                                                   
        Test (); Calc_time = 100
        0000;
        SYSTEM.OUT.PRINTLN ("Calculation times:" + calc_time + "----------------------");
    Test ();
                                                                                                      private static void Test () throws Interruptedexception {Testai ();                                                                                                             
        Test
                                                                                                                                                                                                                   
        I ();
    TESTVI ();
        private static void Testai () throws interruptedexception {Testvolatile testvolatile = new Testvolatile ();
        Countdownlatch begsignal = new Countdownlatch (1);
        Countdownlatch endsignal = new Countdownlatch (thread_num); for (int i = 0; i < Thread_num i++) {new THREAD (testvolatile.new Workerai (begsignal, endsignal)).
        Start ();
                                                                                                                                                                                            Long starttime = System.currenttimemillis ();                    
        Begsignal.countdown ();
                                                                                                                                                                                                                   
        Endsignal.await ();  Long
                                                                                                                                                                                                            Endtime = System.currenttimemillis ();
    SYSTEM.OUT.PRINTLN ("Total time consumed by atomic increment:" + (Endtime-starttime)); private static void Testi () throws interruptedexception {Testvolatile testvolatile = new Testvo
        Latile ();
        Countdownlatch begsignal = new Countdownlatch (1);
                                                                                         Countdownlatch endsignal = new Countdownlatch (thread_num);                                                                                                                          for (int i = 0; i < Thread_num i++) {new THREAD (testvolatile.new workeri begsignal
        gnal)). Start ();
                                                                                                                                                                                            Long starttime = System.currenttimemillis ();
        Begsignal.countdown ();
                                                                                                                                                                                                                   
        Endsignal.await ();  Long
                                                                                                                                               Endtime = System.currenttimemillis ();                                                                    
        SYSTEM.OUT.PRINTLN ("Total time consumed by Sy")
    Nchronized Increment: "+ (Endtime-starttime));"
                                                                                                                                                                                                               
    }
            private static void Testvi ()
        Throws Interruptedexception {Testvolatile testvolatile = new Testvolatile ();
        Countdownlatch begsignal = new Countdownlatch (1);
                                                                                                                                                                                        Countdownlatch endsignal = new Countdownlatch (thread_num); for (int i = 0; i < Thread_num i++) {New THREAD (TESTVOLATILE.N
        EW Workervi (begsignal, endsignal)). Start ();Long starttime = System.currenttimemillis ();
        Begsignal.countdown ();
                                                                                                                                                                                                                   
        Endsignal.await ();  Long
                                                                                                                                                                                                            Endtime = System.currenttimemillis ();
    SYSTEM.OUT.PRINTLN ("Total time consumed by volatile increment:" + (Endtime-starttime));
    public void Incrai () {ai.getandincrement (); } public synchronized void incrI () {i++;
    /** * This function is not thread safe and is likely to get the wrong result, only to test the efficiency of reading the volatile variable/public void Incrvi () {vi++;
        Class Workerai implements Runnable {private Countdownlatch beginsignal;
        Private Countdownlatch endsignal;
            Public Workerai (Countdownlatch begin, Countdownlatch end) {this.beginsignal = begin;
        This.endsignal = end;
            @Override public void Run () {try {beginsignal.await ();
            catch (Interruptedexception e) {e.printstacktrace ();
            for (int j=0; j<calc_time; j) {Incrai ();
                                                                                                                                                                                                                       
            } Endsignal.coun
        Tdown (); } class Workeri implementsRunnable {private Countdownlatch beginsignal;
        Private Countdownlatch endsignal;
            Public Workeri (Countdownlatch begin, Countdownlatch end) {this.beginsignal = begin;
        This.endsignal = end;
            @Override public void Run () {try {beginsignal.await ();
            catch (Interruptedexception e) {e.printstacktrace ();
            for (int j=0; j<calc_time; j) {Incrai ();
        } endsignal.countdown ();
        } class Workervi implements Runnable {private Countdownlatch beginsignal;
        Private Countdownlatch endsignal;
            Public Workervi (Countdownlatch begin, Countdownlatch end) {this.beginsignal = begin;
        This.endsignal = end;
            @Override public void Run () {try {beginsignal.await (); catch (InterruptedeXception e) {e.printstacktrace ();
            for (int j=0; j<calc_time; j) {Incrvi ();
        } endsignal.countdown (); }
    }
}

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.