1

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

shmosel
  • 49,289
  • 6
  • 73
  • 138
Brijendar Bakchodia
  • 1,567
  • 1
  • 9
  • 15
  • How is this question different from your [recent previous question](https://stackoverflow.com/questions/52339070/condition-in-class-body)? – Hovercraft Full Of Eels Sep 14 '18 at 21:36
  • @HovercraftFullOfEels, can you explain how you find it even close to same? There is literally nothing similar between the questions... – Brijendar Bakchodia Sep 14 '18 at 21:36
  • Why do you think that ReadWriteLock fits well here? See for example https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java – algrid Sep 14 '18 at 22:55
  • @algrid, Actually, I believe it does fit. We can have 1,000,000 threads do a peek() so readlock is useful here, but only 1 can offer/poll at a time so thats why I believe readwritelock is useful – Brijendar Bakchodia Sep 14 '18 at 23:46

0 Answers0