Monitor usage of daily learning 20170701--guava concurrency compilation

Source: Internet
Author: User
Tags readable
Order

The Monitor class is an alternative to Reentrantlock, where the use of monitor is less error-prone, more readable, and has no significant performance penalty than using reentrantlock, and even potential performance is optimized using monitor. Below we overall on the monitor's source code structure to do a comb, in general also in the JDK from the most original wait, notify. Another layer of warp. Provides a richer API. Native Implementation

Now suppose that we are going to thread-safe read and write operations on a variable, the native JDK code is implemented as follows:

public class Semaphore {
    private String value;
    Public synchronized String get () throws Interruptedexception {
        while (null = = This.value) {
            wait ();
        }
        string result = new String (this.value);
        This.value = null;
        Notifyall ();
        return result;
    }
    Public synchronized void Set (String value) throws Interruptedexception {while
        (null! = This.value) {
            wait (); c15/>}
        this.value = value;
        Notifyall ();
    }
}
Reentrantlock Implementation

The problem now is that, if there are multiple read threads and write threads at the same time, the native way cannot support finer concurrency control. For example, when a write thread writes, it only wants to wake up the read thread, and the native Notifyall method attempts to wake up all the waiting threads, inevitably raising the competition between all the read and write threads. And the meaning of the code itself is not friendly enough. If you use condition, you can solve this problem very well. The code is as follows:

public class Multicondition {private String value;
    Private final Reentrantlock lock = new Reentrantlock (); Private final Condition valuepresent = Lock.newcondition ();//read Condition private final Condition valueabsent = lock
        . Newcondition ();//write condition public String get () throws Interruptedexception {Lock.lock ();
            try {while (value = = null) {//Read thread waits for valuepresent.await ();
            The String result = value;
            value = NULL;
            When value is set to NULL, the specified wake-up write condition.
            Valueabsent.signal ();
        return result;
        } finally {Lock.unlock ();
        }} public void set (String newvalue) throws Interruptedexception {Lock.lock ();
            The try {while (value! = null) {//value also exists, cannot be written, and the write thread waits for valueabsent.await ();
            } value = NewValue;
 Specifies the wake-up read thread, which represents a readable           Valuepresent.signal ();
        } finally {Lock.unlock (); }
    }
}
Monitor Implementation

As a result, the code can clearly see the concurrent scheduling between the read-write threads, but the condition in this case is only represented by the use of multiple semaphores, but the condition itself has no real conditional meaning. Next look at using the notation of monitor:

public class Monitorsample {
    private String value;
    Private Monitor monitor = new monitor ();
    Private Monitor.guard put = new Monitor.guard (Monitor) {
        @Override public
        boolean issatisfied () {
            return NULL = = value;
        }
    };
    Private Monitor.guard get = new Monitor.guard (Monitor) {
        @Override public
        boolean issatisfied () {
            return Null! = value;
        }
    };
    public void Set (String value) throws Interruptedexception {
        monitor.enterwhen (put);
        This.value = value;
        Monitor.leave ();
    }
    Public String get () throws Interruptedexception {
        monitor.enterwhen (get);
        string result = new string (value);
        value = null;
        Monitor.leave ();
        return result;
    }
}

This approach is similar to the try lock approach. As can be seen, more intuitive than condition, each guard can set a threshold to release, when any one guard reached the condition, it will be awakened. In addition, Moniter also provides more APIs.more APIsEnter (): Enter the current monitor and block indefinitely. Enterinterruptibly (): Enters the current monitor, blocks indefinitely, but may be interrupted. Enter (long time, Timeunit unit): Enters the current monitor, blocking up to a given period, and returning to monitor. Enterinterruptibly (long time, Timeunit unit): Enters the current monitor, blocking up to the given period, but may be interrupted to return to monitor.
TryEnter (): Immediately enter monitor without blocking and return to monitor if possible. Enterwhen (Guard Guard): When the Guard's issatisfied () is true, it enters the current monitor, blocks indefinitely, but may be interrupted. Enterwhenuninterruptibly (Guard Guard): When the Guard's issatisfied () is true, it enters the current monitor and blocks indefinitely. Enterwhen (guard guard, long time, Timeunit unit): When the Guard's issatisfied () is true, it enters the current monitor, blocking up to the given time, This time includes the time to acquire the lock and the time to wait for the guard satisfied, but may be interrupted. Enterwhenuninterruptibly (guard guard, long time, Timeunit unit): When the Guard's issatisfied () is true, it enters the current monitor, blocking up to the given time, This time includes the time to acquire the lock and the time to wait for the guard satisfied. Enterif (Guard Guard): If the Guard's issatisfied () is true, enter the current monitor and obtain the lock indefinitely without waiting for the guard satisfied. Enterifinterruptibly (Guard Guard): If the Guard's issatisfied () is true, enters the current monitor, obtains the lock indefinitely, does not need to wait for the guard satisfied, but may be interrupted. Enterif (guard guard, long time, Timeunit unit): If the Guard's issatisfied () is true, enters the current monitor, holds the lock for a given time, does not need to wait for guard Satisfied. Enterifinterruptibly (guard guard, long time, Timeunit unit): If the Guard's issatisfied () is true, enter the current monitor and hold the lock for a given time, There is no need to wait for guard satisfied, but may be interrupted. Tryenterif (Guard Guard): If the ISSATISFI of the GuardEd () is true and can immediately enter monitor without waiting for a lock or waiting for guard satisfied. WaitFor (Guard Guard): Waits for guard satisfied, waits indefinitely, but may be interrupted when a thread currently occupies monitor, the method may be called. Waitforuninterruptibly (Guard Guard): Waits for guard satisfied, waits indefinitely, the method may be called when a thread currently occupies monitor. WaitFor (guard guard, long time, Timeunit unit): Waits for the guard satisfied, waits within a given time, but may be interrupted, and the method may be called when a thread currently occupies monitor. Waitforuninterruptibly (guard guard, long time, Timeunit unit): Waits for the guard satisfied, waits within a given time, when a thread currently occupies monitor, The method is not likely to be called. Leave (): Out of the current monitor, this method may be called when a thread currently occupies monitor. Isfair (): Determines whether the current monitor uses a fair sorting strategy. Isoccupied (): Returns whether the current monitor is occupied by any thread, this method is suitable for detecting system State and not for synchronization control. Isoccupiedbycurrentthread (): Returns whether the current thread occupies the current monitor. Getoccupieddepth (): Returns the number of times the current thread has entered monitor, and returns 0 if the room front path does not occupy monitor. Getqueuelength (): Returns an estimated number of threads waiting to enter monitor, just an estimate, because the number of threads may change dynamically when the method accesses that data structure. This method is suitable for detecting system State and not for synchronization control. Getwaitqueuelength (Guard Guard): Returns an estimated number of threads waiting for a given Guard satisfied, note that because timeouts and interrupts can occur at any time, it is estimated to be only the upper limit of the actual number of waiting threads. This method is suitable for detecting system State and not for synchronization control. Hasqueuedthreads (): Returns whether any threads are waiting to enter this monitor, note that because cancellation can occur at any time, the returnReturning true does not guarantee that any other thread will enter this monitor. This method is designed to detect system state. Hasqueuedthread (thread thread): Returns whether a given thread is waiting to enter this monitor, note that because cancellation can occur at any time, returning true does not guarantee that a given thread will enter this monitor. This method is designed to detect system state. Haswaiters (Guard Guard): Returns whether any thread is waiting for a given Guard satisfied, note that because cancellation can occur at any time, returning true does not guarantee that a future Guard becomes satisfied when any thread is awakened. This method is designed to detect system state.

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.