Saturday, 9 April 2016

What is Semaphore and its usage ?


Semaphores 
  • used to control number of activities
  • Number of permits are passed to Semaphore constructor.
  • Activities can use acquire() or release() method to acquire / release the permit.
  • If no permit is available, acquire blocks until any one permit is available.


Use case 1. Resource pool - like, Connection pool
  • Initialize a Semaphore to the pool size
  • acquire a permit before trying to fetch a resource from the pool
  • release the permit after putting a resource back in the pool
  • acquire blocks until the pool becomes nonempty

Use case 2. 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

No comments:

Post a Comment

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