Talk about high concurrency (18) Understanding Atomicxxx.lazyset Methods

Source: Internet
Author: User

Read the java.util.concurrent.atomic bag inside each atomicxxx class implementation of students should have seen lazyset methods, such as Atomicboolean class Lazyset method

Public final void Lazyset (Boolean newvalue) {
        int v = newvalue 1:0;
        Unsafe.putorderedint (this, valueoffset, V);
    }

Its underlying implementation calls the unsafe Putorderedint method to see the Javadoc of putorderedxxx methods

It means that the Putorderedxxx method is a deferred implementation of the Putxxxvolatile method and does not guarantee that the value changes are immediately visible to other threads

<span><span><span style= "FONT-FAMILY:CALIBRI;FONT-SIZE:12PX;"  >/***    * Sets The value of the integer field at the specified offset in the    * supplied object To the given value.  this is a ordered or lazy    * version of of <code>putintvolatile (Object,long,int ) </code&gt, which    * doesn ' t guarantee the immediate visibility of the the ' Change to '    * thre ads.  It is only really useful where the integer field is    * &LT;CODE&GT;VOLATILE&LT;/CODE&GT;, and is th
US expected to change unexpectedly.    * Sets the value of the integer field corresponding to the offset offset address in the Obj object as the specified value. This is an ordered or    * has a delayed <code>putIntVolatile</cdoe> method, and does not guarantee that the value changes by other lines Chengli    * that is seen.
It is only useful when field is <code>volatile</code> modified and expected to be accidentally modified by    * use.
   *    * @param obj The object containing the field to modify.    *     contains objects that need to be modified field    * @param offset theOffset of the integer field within <code>obj</code>.    *       <code>obj</code> offset of integer field    * @param value the
New value of the field.    *      field will be set the new value    * @see #putIntVolatile (object,long,int)    */</span></span></span> <span><span><span style= "font-family:Calibri;font-size : 12px; "
 > Public native void Putorderedint (Object obj, long offset, int value);</span></span></span>


Understand volatile the bottom of the implementation of the students know that the implementation of the volatile is finally added a memory barrier,

1. Guaranteed write volatile variable will force the CPU writes the buffer data to flush to the memory

2. Read the volatile variable, invalidate the cache, forcing the most recent value to be read from memory

3. Because of the memory barrier, the volatile variable can also prevent reordering


Therefore, the modification of the volatile variable can immediately make all threads visible and ensure visibility. Instead of volatile variables, JMM does not guarantee that changes to normal variables are immediately visible to all threads. So Lazyset plainly is to write variables in the form of ordinary variables.

Modifications to Flaga are immediately visible to all threads
volatile Boolean Flaga;
Modifications to FLAGB cannot be immediately visible to other threads by
Boolean FLAGB;

So why do you need a Lazyset method? In fact, it is a low-level optimization method, for the upper-level callers, in fact, rarely used. Here is a scene with Lazyset.

In this chat high concurrency (16) Implementation of a simple reentrant lock we have implemented a reentrant lock in which shared variables are used with volatile variables to ensure that changes to shared variables are visible to other threads.


But in fact, it's perfectly possible to decorate these shared states without volatile variables,

1. Because access to the shared state is preceded by a lock, the Lock.lock () method obtains the lock, and the operation of the lock and the read operation of the volatile variable forces the CPU cache to fail, forcing the variable to be read from memory.

2. Lock.unlock () method to release the lock, as with write volatile variable, will force flush CPU write buffer, write cache data to main memory

The bottom layer is also implemented by adding a memory barrier.


Package com.zc.lock;  
Import java.util.concurrent.locks.Condition;  
  
  
Import Java.util.concurrent.locks.ReentrantLock; /** * Simple reentrant Lock implementation, using a counter to record the number of times the current thread is locked, get the counter plus 1 lock, release the lock counter minus 1, when the counter is equal to 0 when the release of the lock * **/public class Simplereentrantlock Implem  
      
    Ents lock{//point to the thread that has acquired the lock private volatile thread exclusiveownerthread;  
      
    The record acquires the same number of locks as the private volatile int holdcount;  
      
    Private final Java.util.concurrent.locks.Lock Lock;  
      
    Whether is oneself obtains the condition of the lock private final Condition Iscountzero;  
        Public Simplereentrantlock () {lock = new reentrantlock ();  
        Iscountzero = Lock.newcondition ();  
    Holdcount = 0;  
        @Override public void Lock () {lock.lock ();  
            try{//When the thread of reference thread CurrentThread = Thread.CurrentThread (); If the thread that gets the lock is itself, then the counter adds 1, directly returns if (Exclusiveownerthread = = CurrentThread) {HOLDCOunt + +;  
            Return  
                while (holdcount!= 0) {try {iscountzero.await ();  
                catch (Interruptedexception e) {throw new RuntimeException ("interrupted"); }//Set Exclusiveownerthread to own Exclusiveownerthread = Currentth  
            Read  
        Holdcount + +;  
        }finally{Lock.unlock ();   }  
    }

The use of Lazyset () and the above optimization is a truth, that is, if you do not need to make changes to the shared variables immediately to make other threads visible, to set common variables to modify the shared state, you can reduce the unnecessary memory barrier, thereby increasing the efficiency of program execution.

The following example comes from a question on StackOverflow that is similar to the idea of optimizing unnecessary volatile operations. By the wall of the students can not see the screenshot.


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.