Volatale of Java Thread Safety (vii) __java

Source: Internet
Author: User
Tags volatile
Technology News

November 16 Evening News, Ctrip CEO Sun Jie on the parent-child Park event related progress to do final bulletin, Ctrip former vice president of human Resources Shi, the current vice president of human Resources Feng Weihua has been dismissed. Body

Although the volatile keyword has visibility between multiple threads, but does not have synchronization (i.e., atomicity), it can be considered a lightweight synchronized that performs much better than synchronized and does not cause congestion (in many open source architectures, For example, the Netty of the underlying code to use a lot of volatile, visible netty performance must be very good. Note here: The general volatile is used for variable operations that are visible only to multiple threads and cannot replace the synchronized synchronization function. The following cases:

public class Volatilenoatomic extends Thread {
    //private static volatile int count;
    private static Atomicinteger count = new Atomicinteger (0);

    private static void Addcount () {
        //count++;
        Count.incrementandget ();

        System.out.println (Thread.CurrentThread (). GetName () + "  >>>>  " + count);
    }

    public void Run () {
        addcount ();
    }

    public static void Main (string[] args) {

        volatilenoatomic[] arr = new volatilenoatomic[100];
        for (int i = 0; i < i++) {
            Arr[i] = new Volatilenoatomic ();
        }

        for (int i = 0; i < i++) {
            arr[i].start ();}}
        }


Print results (each time the results will be different):
Thread-1  >>>>  3
Thread-2  >>>>  3
Thread-0  >>>>  3
Thread-3  >>>>  4
Thread-4  >>>>  5
Thread-5  >> >>  6
Thread-6  >>>>  7
Thread-7  >>>>  8
Thread-8  >>>>  9
Thread-9  >>>>  10
Sample Summary

The volatile keyword is only visible and has no atomic nature. To achieve atomicity it is recommended to use series objects of the atomic class to support atomic operations (note that the atomic class only guarantees its own method atomicity and does not guarantee the atomicity of multiple operations)

The following cases:

public class Atomicuse {private static Atomicinteger count = new Atomicinteger (0); Multiple addandget are not atomic in one method and require synchronized to be modified to guarantee 4 Addandget overall atomicity/**synchronized*/public synchronized int Multiad
            D () {try {thread.sleep (1000);
            catch (Interruptedexception e) {e.printstacktrace ();
            Count.addandget (1);//+1 Count.addandget (2);//+3 Count.addandget (3);//+6 Count.addandget (4);
    +10 is a plus return count.get ();

        public static void Main (string[] args) {final atomicuse au = new Atomicuse ();
        list<thread> ts = new arraylist<thread> ();
                for (int i = 0; i < i++) {Ts.add (New Thread () (new Runnable () {@Override public void Run () {System.out.println () Thread.CurrentThread (). GetName () + ">>>>" +au.m
        Ultiadd ());        }
            }));
        for (Thread t:ts) {T.start (); }
    }
}

Print results:

Thread-0   >>>>
Thread-9   >>>>
Thread-8   >>> >
Thread-7   >>>>
Thread-6   >>>>
Thread-5   >>>>
Thread-4   >>>>
Thread-3   >> >>
Thread-2   >>>>
Thread-1   >>>>   100

Multiple addandget are not atomic in one method and need to be modified with synchronized to guarantee 4 Addandget overall atomicity

Source code: HTTPS://GITHUB.COM/HFBIN/THREAD_SOCKET/TREE/MASTER/THREAD/SYNC007

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.