Suppose I have a servlet that on doPost method performs some actions. Also I have some pool of Connections(let it be N connections) to some web-service that are taken from the pool on each request to my servlet(1 connection per request). In doPost method of the servlet I retrieve a connection from the pool, use it(this operation may last too long) and put back it to the pool.
Suppose that N connections are made simultaneously to the servlet, so N connections will be retrieved from the pool. And while that requests are being processed, N+1 and N+2 requests are arrived, so they will wait until releasing of some connection occurs(my pool is backed by BlockingQueue).
I want to guarantee that N+1 request will own the available connection earlier than N+2 request.
How can I achieve this?
ArrayBlockingQueueprovides constructor argument to control fairness of the queue – when set totrue, it’s guaranteed that threads will get elements of the queue in the same order as they calledtake().As far as I understand, use of
ArrayBlockingQueuewithfair = trueas a backing queue of your pool should be enough for your case.