Saturday, 9 April 2016

How to use Semaphore to implement a Bounded and blocking collection ?


Use case. Bounded + blocking collection
  • Initialize a Semaphore to max size of collection
  • add acquires the permit before adding item
  • remove releases permit so that more items can be added

Example
Define semaphore
Semaphore semaphore = new Semaphore(MAX_SIZE);

Add operation
semaphore.acquire();
// Add item
semaphore.release();

Remove operation 
// Remove item
semaphore.release();

No comments:

Post a Comment

Note: only a member of this blog may post a comment.