I'm working on scheduling the tasks on a thread pool. My requirement is that each task will iterate the same logic up to 4 times but before each iteration if some condition is satisfied I want to terminate the task.
Scheduling the task->
ScheduledExecutorService scheduledExecutorService;
// Submitting the task to the thread pool
scheduledExecutorService.scheduleAtFixedRate(new Task(payload),
AppConstants.INITIAL_DELAY_IN_MINUTES,
AppConstants.INTERVAL_BETWEEN_DELIVERY_IN_MINUTES,
TimeUnit.MINUTES);
The run method of the Task class (implements Runnable)->
@Override
public void run() {
if (shouldTaskTerminate())
terminateTask("Counter reached it's upper bound for " + payload.getEventId());
// Handling the task if the above condition is not satisfied
}
private void terminateTask(String taskTerminationReason) {
log.info(" {}. So, cancelling the task of {} ", taskTerminationReason, Thread.currentThread().getId());
throw new RuntimeException("Task lifecycle completed.");
}
As mentioned in the above code snippet, I am throwing an exception to terminate the task. I got to know this way of terminating the task by referring to the JavaDoc here.
Is this the correct way of terminating the task? I also got to know that another way of terminating the task is canceling the future object whenever I submit the task to the thread pool. But, in my case, I want to terminate it within the Task class (i.e. Runnable implementer) because the variables/database queries defined in the Task class decide the future run.