Java language multithreading visibility (synchronized and volatile learning)

Source: Internet
Author: User

The principle of shared variable visibility implementation
Implementation of visibility supported by the Java language level: synchronized volatile


1, the synchronized two provisions:
Before 1-Wire threads unlocked, you must flush the latest value of the shared variable to main memory.
2-wire Cheng, the value of the shared variable in the working memory is emptied, so the most recent value needs to be reread from main memory when using shared variables (locking and unlocking need to be the same lock)
Changes to shared variables before line threads unlocked are visible to other threads the next time the lock is added.

2, volatile realization of visibility
In depth, this is achieved by adding a memory barrier and prohibiting reordering optimizations .
When a write operation is performed on a volatile variable, a store barrier instruction is added after the write operation.
When a read operation is performed on a volatile variable, a load barrier instruction is added before the read operation.
In layman's terms, a volatile variable is forced to reread the value of the variable from main memory each time it is accessed by a thread, and when that variable changes, it
Forcing a thread to flush the latest values into main memory so that at any point in time, different threads can always see the latest value of the variable.
But volatile does not guarantee the atomicity of variables.

Typical num++ operation, when using volatile modifier variables, cannot save the atomic nature of the operation, so there will be many values.
If this is the case, then the workaround is to use volatile:

Use the Synchronized keyword for wrapping. Reentrantlock the lock before the code, and then uses unlock to release the lock.

Pay attention to special occasions when using volatile:

    • 1, the write operation to the variable does not depend on its current value. Typical is numb++ \ Num=num*3 and so on.
    • 2. The variable is not included in the invariant with other variables. (for example, two volatile variables exist in a size relationship, or other relationships are medium)

3, synchronized and volatile comparison

    • 1, volatile does not need to lock, more than synchronized level, will not block the thread.
    • 2, from the perspective of memory visibility, volatile read equivalent to lock, volatile write equivalent to unlock.
    • 3, synchronized can guarantee the visibility, but also to ensure atomicity, and volatile can only guarantee visibility, can not guarantee atomicity.

code example:

 PackageOrg.apple.thread;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classVolatiletest {PrivateLock lock =NewReentrantlock (); Private volatile intNumber = 0;  Public voidIncrease () {this.number++; //The second way of solving//Lock.lock ();//this.number++;//Lock.unlock (); //The first of these solutions//synchronized (this) {//this.number++; //}    }         Public intGetNumber () {return  This. number; }    /**     * @paramargs*/     Public Static voidMain (string[] args) {FinalVolatiletest volatiletest =Newvolatiletest ();  for(inti = 0; I < 500; i++) {            NewThread (NewRunnable () {@Override Public voidrun () {volatiletest.increase ();        }}). Start (); }        //if the current thread still has child threads running, the main thread will make up the CPU resources until all the child threads have finished running, then proceed down.         if(Thread.activecount () >1) {Thread.yield ();        } System.out.println (Thread.activecount ());    System.out.println (Volatiletest.getnumber ()); }}

Java language multithreading visibility (synchronized and volatile learning)

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.