Java synchronization mechanism: policy vs policyall

Source: Internet
Author: User
Use the wait-and-policy mechanic to deal with synchronized accessing a resource

Wait-and-PolicyMachism:
1 wait & Policy canNeverBeOutSynchronized block of the releated-object (the wait and notify methods must beCorresponding object)
2 wait can release & get the lockAutomatically

TheDifferenceBetween between Y and policyall
1 When Y is wake the thread which invoke the wait-Method
2 policyall is wake all the thread waiting for the lock released
3 Why can form the thread invoking the wait-method and threads waiting for the lock released?
We know, ifSynchronized MethodIs invoked, all the other synchronized methods belong to the object can not be invoked, so the invoking threads must be blocked, and waiting the method can be invoke, so they all waite for the lock released in the list of waiting queue.
ASynchronized classIs the same;
When the specified y method occurs, the waiting one who invoked wait () be wake;
When the policyall method occurs, the waiting queue choose the most prior one to wake, can be the one invoking wait (), also can be the ones waiting the lock released;

What we should be care?
If one waiting thread is waked, its waiting condition may not be satisfied. And in the right way, it shoshould wait continuely.
How we assure this route?
-- Just as follows came from <valid tive Java> and <practical Java>
The former: never invoke wait outside a loop
Eg:
 

1 synchronized (OBJ ){
2 while (<condition does not hold> ){
3 Wait ();
4 // perform action appropriate to Condition
5}
6}

The later: Use spin locks to deal with wait and policyall

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.