java - Condition give the effect of having multiple wait-sets per object? -


i reading condition in java.util.concurrent.locks.condition .

condition factors out object monitor methods (wait, notify , notifyall) >into distinct objects give effect of having multiple wait-sets per object, combining them use of arbitrary lock implementations.

can explain me this?

how benefit on normal synchronization blocks or method?

one lock can associated many conditions. lock "object", each condition "waiting set". allows independent conditions sharing critical section. example, consider bounded producers-consumers problem. 1 way solve have 1 lock protects queue, , 2 independent waiting sets: 1 producers, waiting slot place item in queue, other consumers waiting items take. using plain old synchronized , wait/notify api, best can along these lines:

  • producer:

    synchronized (lock) {     while (queue.isfull()) {         lock.wait();     }     queue.put(sth);     lock.notify(); } 
  • consumer:

    synchronized (lock) {     while (queue.isempty() {         lock.wait();     }     product = queue.take();     lock.notify(); } 

this has disadvantage of waking both producers , consumers on every change queue, if cannot possibly allow given thread proceed (e.g. consumer awoken when other consumer takes item queue). using lock/condition api can implement solution separates waiting consumers , producers, , hence reduce redundant wakeups , checking:

lock lock = new reentrantlock(); condition hasplace = lock.newcondition(); condition hasitems = lock.newcondition(); 
  • producer:

    lock.lock(); try {     while (queue.isfull()) {         hasplace.await();     }     queue.put(sth);     hasitems.signal(); } {     lock.unlock(); } 
  • consumer:

    lock.lock(); try {     while (queue.isempty()) {         hasitems.await();     }     product = queue.take();     hasplace.signal(); } {     lock.unlock(); } 

this way, consumer waits producers produce item (hasitems condition), , upon removing item queue notifies producers there empty slot (hasplace condition). both conditions associated same critical section (lock), keep usual exclusion , release-lock-while-waiting guarantees, while gaining ability separate waiting queues.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -