Java Executor to execute one Callable after previous has finished?

881 views Asked by At

I have a custom business requirement. I need to execute a series of service calls. Each of these call creates a new record in the database. I need to execute the next service call only after the previous service call has finished, because the new service call will use the record created in the DB by previous service call, as a input parameter.

I had decided to wrap each of these service calls in a Future Tasks and then use Executors.newSingleThreadExecutor() to execute these tasks in a loop.

Please suggest will it suffice and a better solution if it will not ??

Also do I need to place task.isDone() before executing the next task??

1

There are 1 answers

0
fge On

I have decided to use Executors.newSingleThreadExecutor().

Good choice given your requirement.

Please suggest will it suffice and a better solution if it will not ??

Yes, pretty much so. With the standard JDK libraries, this is probably the best you can find.

Also do I need to place task.isDone() before executing the next task??

No. The javadoc for this executor explicitly states that "[...]Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time."

Therefore, no task will be initiated before the previously active one terminates (successfully or not). Just stuff them into the executor, it will handle things for you.