Question

Here is the scenario:

I have a java main process, which uses JMS to publish to some ActiveMQ broker.

Each time a message is supposed to be sent to the broker, a thread is used from a fixed sized thread pool (using ThreadExecutor) and inside it the publish calls are made.

Now , a publish call is a blocking call and if the broker is down , the thread itself keeps waiting.

I want to create a threadpool such that if a specific thread is not over with the task in X amount of time, it simply returns i.e if the broker is down and the publish does not go through, the thread does not keep waiting and instead return to the pool.

There is no way as of now to make this publish call Asynchronous, so the only way to handle this situation is the one mentioned above I guess.

Are there any ThreadExecutors out there which allow me to terminate a thread immidiately, if the thread is not able to complete a task in a given timeframe??

Would love a more elegant solution from someone.

Was it helpful?

Solution

The ExecutorService interface offers the methods invokeAll() and invokeAny() with a timeout parameter.

Example:

ExecutorService executor = Executors..newFixedThreadPool(2);
executor.invokeAll(Arrays.asList(new Callable<Void>(){

    @Override
    public Void call() throws Exception {
        try {
            // do your task
        } catch (InterruptedException e) {
            // your task was forced to end
        }
        return null;
    }

}), 5, TimeUnit.SECONDS);
executor.shutdown();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top