How to wait for events when using StampedLock?

Viewed 28

Java's StampedLock does not support Condition variables. As such, how can one implement the following pseudo code with StampedLocks?

public class Example
{
    private final List<Integer> queue = new ArrayList<>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock writeLock = lock.writeLock();
    private final Condition dataAdded = writeLock.newCondition();

    public void waitForData()
    {
      writeLock.lock();
      try
      {
        while (queue.isEmpty())
          dataAdded.await();
      }
      finally
      {
        writeLock.unlock();
      }
    }
}

Specifically, how do I wait on the event without condition variables? The only approaches that come to mind are:

Old-school Object.wait():

Object dataAdded = new Object();

public void waitForData()
{
  synchronized (dataAdded)
  {
    while (queue.isEmpty())
      dataAdded.wait();
  }
}

ReentrantLock with a corresponding Condition:

Lock writeLock = new ReentrantLock();
Condition dataAdded = new Condition();

public void waitForData()
{
  writeLock.lock();
  try
  {
    while (queue.isEmpty())
      dataAdded.await();
  }
  finally
  {
    writeLock.unlock();
  }
}

It seems kind of odd to use multiple locking mechanisms to achieve this. Further, when I come back from wait() or await() I am not guaranteed to be able to acquire a StampedLock write lock.

Thoughts?

0 Answers
Related