Search code examples
javaspringspring-mvcjava-ee-6quartz-scheduler

Spring ThreadPoolTaskExecutor configuration?


i am using Spring 2.5 ThreadPoolTaskExecutor as below.

<bean id="taskExecutor"
    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>

java code:

ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
    taskExecutor.execute(new PrintTask("Thread 1"));
    taskExecutor.execute(new PrintTask("Thread 2"));
    taskExecutor.execute(new PrintTask("Thread 3"));
    taskExecutor.execute(new PrintTask("Thread 4"));
    taskExecutor.execute(new PrintTask("Thread 5"));

Above code works fine without any issues. My problem is, ThreadPoolTaskExecutor is asynchronous, it means it does not wait till the task gets completed. It just fires and forgets. If any of the execute call throws any exception I need to catch it and send an email.

In order to do so, how can I make the process wait till taskExecutor's execute methods gets completed to know whether it throws any exceptions or not?

Also, what is WaitForTasksToCompleteOnShutdown in my configuration?

When can i call taskExecutor.shutdown();? Please help me?

Thanks!


Solution

  • You could call submit() rather than execute() and get a Future back, which would tell you if there was an error; the downside of this is you have to make a blocking call to find the error.

    A better (or at least, more asynchronous) solution is to handle the error within your PrintTask:

    @Override
    public void run() {
        try {
            doPrintTaskStuff();
        } catch (Throwable t) {
            sendEmailAboutException(t);
        }
    }