harschware
harschware

Reputation: 13414

guarantee thread execution order is first come first serve

I have code called from a servlet that calls out to an external service. Of course, no guarantees how long the service will take to return a response. I need to ensure that no more than one call to this service executes at a time, but of course the servlet container can be running concurrent requests to the servlet. I want to guarantee that the priority of requests are processed single file, on a first come first server basis. So it is not enough that my call to the external servlet be synchronized because once the current call is finished there would be no guarantee as to which thread gets in to make the call next.

Any ideas?

Upvotes: 1

Views: 1819

Answers (4)

LiuYan 刘研
LiuYan 刘研

Reputation: 1624

Many utilities in java.util.concurrent are suitable for this situation, Semaphore with fairness setting is another choice

import java.util.concurrent.*;
Semaphore sem = new Semaphore (int n = HOW_MANY_PERMITS, boolean fairness = true);

Upvotes: 1

pingw33n
pingw33n

Reputation: 12510

You can use single-threaded ExecutorService to submit Callables (which will perform actual request) and wait for Future value to become available.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533540

You could use a fair Lock

Lock lock = new ReentrantLock(true);

This gives the lock in the order it was attempted.

Upvotes: 6

Erik
Erik

Reputation: 91270

Create a worker thread in your servlet and enqueue callouts there. Request handling would synchronize on adding a request to the queue, then just sit there waiting for the worker thread to report back.

Upvotes: 0

Related Questions