Java Concurrency--locksupport

Source: Internet
Author: User
Tags cas thread class volatile

Locksupport Overview

Basic thread blocking primitives for creating locks and other synchronization classes. The underlying threading block primitives used to create locks and other synchronization classes. This is the explanation in Java doc, and the following is a framework for a first in, out (first-in-first-out) non-reentrant lock class.

The above code simple implementation of the lock function, mainly using the Locksupport Park and Unpark blocking and releasing threads, Atomicboolean CAS operation to determine whether to hold the lock Concurrentlinkedqueue to save the waiting thread, This queue is a thread-safe queue that is currently removed from the wait queue only if the thread is waiting for the queue first and holds the lock before it jumps out of the while loop.

The semantics of Locked.compareandset (false, True) is that the value of the expected Atomicboolean object is false and the value is set to true to determine whether the lock is held
Locksupport Source
Method Summary
static Object getBlocker(Thread t)
Returns the Blocker object provided to the last park method call that has not been unblocked, or null if the call is not blocked.
static void park()
For thread scheduling, the current thread is disabled unless the license is available.
static void park(Object blocker)
For thread scheduling, the current thread is disabled before the license is available.
static void parkNanos(long nanos)
To disable the current thread for thread scheduling, wait up to the specified wait time, unless the license is available.
static void parkNanos(Object blocker, long nanos)
For thread scheduling, disable the current thread before the license is available and wait up to the specified wait time.
static void parkUntil(long deadline)
For thread scheduling, the current thread is disabled before the specified time limit, unless the license is available.
static void parkUntil(Object blocker, long deadline)
For thread scheduling, the current thread is disabled before the specified time limit, unless the license is available.
static void unpark(Thread thread)
If the license for a given thread is not yet available, make it available.

Locksupport provides all static methods for static modification, which are used as a tool class. It mainly provides methods for blocking threads and unblocking threads.

    Hotspot implementation via intrinsics API    private static final unsafe unsafe = unsafe.getunsafe ();//Holding an instance of unsafe C5/>private static final long parkblockeroffset;  Offset    Static {        try {            parkblockeroffset = Unsafe.objectfieldoffset   //Initialize Get property offset                ( Java.lang.Thread.class.getDeclaredField ("Parkblocker"));        } catch (Exception ex) {throw new Error (ex);}    }

  

In the previous chapter we explored the CAS usage of unsafe, and here again, Locksupport uses the unsafe class to get property modification properties, and Parkblocker is a member variable of the thread class.

    /**     * The argument supplied to the     "current" to * Java.util.concurrent.locks.LockSupport.park.     * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker     * accessed using Java.util.concurrent.locks.LockSupport.getBlocker     */    volatile Object parkblocker;

The same is the volatile modifier, which means blocking the object of the current thread, which gives us a way to monitor how the thread is blocked.

private static void Setblocker (Thread t, Object Arg) {        //Even though volatile, hotspot doesn ' t need a write barrier h ere.        Unsafe.putobject (t, Parkblockeroffset, ARG);    } /**     * Returns the Blocker object supplied to the most recent     * Invocation of a park method which has not yet unbloc ked, or null     * if not blocked.  The value returned is just a momentary     * snapshot – The thread may has since unblocked or blocked on a     * differe NT Blocker object.     *     * @param t the thread     * @return the blocker     * @throws nullpointerexception if argument is null     * @si NCE 1.6     */public    static Object Getblocker (Thread t) {        if (t = = null)            throw new NullPointerException ( );        Return Unsafe.getobjectvolatile (t, parkblockeroffset);//Get property value based on attribute offset    }

Why use unsafe to get the thread's Parkblocker variable instead of getting it through the set and get methods? This is because parkblocker only makes sense when the thread is blocked, and the set and get methods cannot be called through the threading object.

    Public native Object Getobjectvolatile (object var1, long var2);    public native void Putobjectvolatile (object var1, Long var2, Object VAR4),//var2 is the offset of the property in Var1, VAR4 is the property value to set

This is the native method provided by the unsafe class, the concrete implementation here no longer delve into.

The above explores the handling of blocking information in Locksupport, and below is a look at blocking and unblocking functions.

    public static void Park (Object blocker) {        Thread t = thread.currentthread ();//When the front thread        setblocker (t, blocker);//set to be Who blocks        Unsafe.park (false, 0L);  Blocking thread        setblocker (t, null);  Thread unblocked, emptying blocker information    } public    static void Unpark (thread thread) {        if (thread! = null)            Unsafe.unpark (thread);   Unblocking Threads    }

This is the native function of the actual blocking thread and unblocking thread in the unsafe class, var1 indicates whether the time is absolute time or relative time, false is relative time, var2 means unblocking time, set to 0 only if the thread breaks, or the Unpark function is called unlocked. If it is not 0, it will automatically unblock after waiting for var2 time, note that the time unit here is nanosecond; when var1 bit true, the time unit of VAR2 is milliseconds.

    public native void Unpark (Object var1);    Public native Void Park (Boolean var1, long var2);

Wait up to Nanos nanoseconds

    public static void Parknanos (Object blocker, long Nanos) {        if (Nanos > 0) {            Thread t = thread.currentthread (); C5/>setblocker (t, blocker);            Unsafe.park (False, Nanos);            Setblocker (t, null);        }    }

  

Java Concurrency--locksupport

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.