The following code is taken from the JavaDoc of Condition:
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCo
I tested below code with single monitor and below always performs better - Tested on 2 core machine, Condition performance is 10-15% below on an average
final Object sync = new Object();
AtomicInteger add=new AtomicInteger();
AtomicInteger remove=new AtomicInteger();
final Object[] items = new Object[1];
int putptr, takeptr, count;
public void add(Object x) throws InterruptedException {
add.incrementAndGet();
synchronized (sync) {
while (count == items.length)
sync.wait();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
sync.notify();
}
}
public Object remove() throws InterruptedException {
remove.incrementAndGet();
synchronized (sync) {
while (count == 0)
sync.wait();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
sync.notify();
return x;
}
}
public static void main(String[] args) {
final BoundedBuffer bf=new BoundedBuffer();
Thread put =new Thread(){
public void run(){
try {
while(true)
bf.add(new Object());
} catch (InterruptedException e) {
}
}
};
put.start();
Thread take= new Thread(){
public void run(){
try {
while(true)
bf.remove();
} catch (InterruptedException e) {
}
}
};
take.start();
try {
Thread.sleep(1000L);
put.interrupt();
take.interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("add:"+bf.add);
System.out.println("remove:"+bf.remove);