If we want to implement a resource pool such as a database connection pool. Which concurrent collection will you use ? BlockingQueue or Semaphore ?
For BlockingQueue, just like the producer-consumer design pattern, the producer will place all the connections on the queue and the consumer will take next available connection from the queue.
For Semaphore, you specify the semaphore to the pool size, and acquire permit until you reach the pool size and wait for any of them to release the permit and putting the resource back in the pool.
Which one is simpler and easier ? and what are the scenario where we can only use one but not other ?
The BlockingQueue is simpler because it will keep track of the Connections/resource as well.
e.g.
As you can see, the BlockingQueue helps keep track of free resources and ensure there is not too many free resources. It is thread safe without requiring explicit locking.
If you use a Semaphore, you still need to store the resources in a collection (making the semaphore redundant 😉