Swapnil
Swapnil

Reputation: 864

ScheduledExecutorService - Conditionally terminate task

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.

Upvotes: 0

Views: 189

Answers (1)

white-surf-style-five
white-surf-style-five

Reputation: 497

It's a way to terminate the periodic scheduling. I think it's ugly, but It' the simplest thing that can work and I think pragmatism is a virtue.

It's correct? If you want to stop the scheduling and you're fine with how that exception is reflected in the ScheduledFuture returned by the scheduling method, then I'd say you're good to go. Just make sure to document the "why" you're throwing the exception, including the link to the javadoc.

It's not the only way you can do that: I have described 2 alternatives in my response to this question

Upvotes: 1

Related Questions