Reputation: 1299
I am using Lock in my app and I wonder what is monitor in this case:
public class BoundedBuffer {
private final String[] buffer;
private final int capacity;
private int front;
private int rear;
private int count;
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
public BoundedBuffer(int capacity) {
super();
this.capacity = capacity;
buffer = new String[capacity];
}
public void deposit(String data) throws InterruptedException {
lock.lock();
try {
while (count == capacity) {
notFull.await();
}
buffer[rear] = data;
rear = (rear + 1) % capacity;
count++;
notEmpty.signal();
} finally {
lock.unlock();
}
}
In this example when invoking deposit method whole object is monitor or only lock ? This is like using synchronize(this)
which lock whole instance ?
Upvotes: 2
Views: 182
Reputation: 18825
Whole object doesn't have any special meaning here. Monitor means the combination of Lock and Condition so it's possible to atomically perform check and block until something happens, see wiki Monitor.
lock.lock ()
is similar to synchronized
keyword but Lock
gives more flexibility. Among others it can create conditions which allow to notify about full/empty status and are connected to this Lock
.
Upvotes: 2