Question

I followed the advice I found in this post using CountDownLatch and i'm running into a problem. I wrote up this test and ran it and my thread I created blocks when i try to synchronize on lock.

  private CountDownLatch lock = new CountDownLatch(1);

  @Test
  public void testBlock() {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        try
        {
          synchronized(this) {
            this.wait(50);
          }
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
          throw (new RuntimeException(e));
        }
        releaseLock();
      }
    };

    Thread t = new Thread(r);
    t.setDaemon(true);
    t.start();

    waitOnCallback();
  }

  private void releaseLock() {
    synchronized(lock) { // Thread t blocks here
      lock.countDown();
    }
  }

  private void waitOnCallback() {
    synchronized(lock) {
      try
      {
        lock.await();
      }
      catch (InterruptedException e)
      {
        throw new RuntimeException(e);
      }
    }
  }

Why isn't this working?

Was it helpful?

Solution

A CountDownLatch is not an object on which you need to synchronize (i.e. remove the synchronized(lock) blocks). all thread-safety is handled internally to the object itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top