Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  }
}
like image 817
tbroberg Avatar asked Aug 13 '26 08:08

tbroberg


1 Answers

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

like image 166
Bohemian Avatar answered Aug 14 '26 23:08

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!