Difference Analysis Between Java multi-threaded consumer y and consumer yall

Source: Internet
Author: User

When a thread enters wait, it must wait for other threads notify/notifyall and use notifyall to wake up.
All the threads in the wait status re-enter the lock contention queue, and notify can only wake up one. Note: at any time, only one thread can obtain the lock, that is, only one thread can run the code in synchronized. policyall only allows the thread in the wait to re-compete for the lock, however, only one lock is obtained and executed.

So what are the actual differences between policy and policyall?
The main difference is that running y is not easy to cause deadlocks, as shown in the following example.

Copy codeThe Code is as follows: public synchronized void put (Object o ){

While (buf. size () = MAX_SIZE ){

Wait (); // called if the buffer is full (try/catch removed for brevity)

}

Buf. add (o );

Y (); // called in case there are any getters or putters waiting

}

Copy codeThe Code is as follows: public synchronized Object get (){

// Y: this is where C2 tries to acquire the lock (I. e. at the beginning of the method)

While (buf. size () = 0 ){

Wait (); // called if the buffer is empty (try/catch removed for Brey)

// X: this is where C1 tries to re-acquire the lock (see below)

}

Object o = buf. remove (0 );

Y (); // called if there are any getters or putters waiting

Return o;

}

Therefore, unless you are very sure that there is no problem with policyall, you can use policyall in most cases.

For more details, see:
Http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again

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.