In Java, since ReadLocks
cannot have conditions, what is the proper way to use conditions between Read/Write locks
?
Here is my concurrent queue class:
private class ConcurrentQ{
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
Lock readLock = readWriteLock.readLock();
Lock writeLock = readWriteLock.writeLock();
Condition emptyList = writeLock.newCondition();
Queue<Integer> list = new LinkedList<>();
/* */
public void push(int x, int thread){
try{
writeLock.lock();
list.offer(x);
emptyList.signalAll();
} catch (Exception ex){
} finally {
writeLock.unlock();
}
}
//Must look at empty case
public void pop(int thread){
int val = -1;
try{
writeLock.lock();
val = list.poll();
} catch (Exception e){
} finally {
writeLock.unlock();
}
}
public void peek(int thread){
int val = -2;
try{
readLock.lock();
while(list.isEmpty())
emptyList.await(); //////PROBLEM HERE!
val = list.peek();
} catch (Exception e) {
} finally {
readLock.unlock();
}
}
}
There is a problem here. Since ReadLock
cannot have conditions, I added a condition in the WriteLock
BUT I cannot call it inside a block where I am using readLock.lock() ... readLock.unlock()
so what can I do? In my peek()
method I want to wait if the list
is empty.
Thanks