tbroberg
tbroberg

Reputation: 635

Java unbounded counted semaphore?

I need to provide a method that blocks until all outstanding work in a BlockingQueue has been processed.

I was thinking I could handle this with a counted semaphore which would start at 0 and decrement as items are added to the queue and increment as they are completed. finish() would just acquire the semaphore, release it again and leave.

I could perhaps call reducePermits(). Does this work if permit count is already < 0? It's protected, so I would need to extend the Semaphore class to make it work.

My second best idea is to check the contents of the queue in a loop and sleep 100ms or so between checks. It works but seems kludgey.

Does this make sense? Anybody have an easier / cleaner way to suggest?

TIA, - Tim.

public MyClass {
  public class MySemaphore extends Semaphore {
    public void seize() {
      reducePermits(1);
    }
  }
  private MySemaphore allDone = new MySemaphore();
  void startSomething() {
    allDone.seize();
  }
  void finishSomething() {
    allDone.release();
  }
  void finish() {
    allDone.acquire();
    allDone.release();
  }
}

Upvotes: 3

Views: 557

Answers (1)

Bohemian
Bohemian

Reputation: 425003

You could drain the queue by calling drainTo(collection), then invoke processing yourself on all items (possibly via Futures etc), then your final processing.

Upvotes: 2

Related Questions