3

Suppose that we have a Java Task (e.g.: Runnable) that will be executed if we do not receive an external signal in x seconds.

A common way to solve this problem is to use a schedule thread pool (such as ScheduledExecutorService) to execute this task considering x delay. When we receive that external event, from other part of the system, we need to reschedule this task, that is, to reinsert this task in the thread pool with x delay.

My question is: what is the correct/optimized way to reschedule a task in a ScheduleExecutorService? Current solutions usually focus on removing/canceling and reinserting the dealyed task in the thread pool. Is this the best approach?

Marcos Roriz Junior
  • 4,076
  • 11
  • 51
  • 76
  • I wouldn't worry too heavily about "optimized" unless you have profiled and know this is causing trouble. Seems easiest to just keep a reference to the previous task you did, cancel it, and schedule a new one replacing the old reference. What other sort of approach would you have in mind? – Josh Berry Jul 14 '14 at 22:41
  • 1
    Googling for "debouncing" seems to indicate people doing the same thing, btw. http://stackoverflow.com/questions/18723112/cancelling-method-calls-when-the-same-method-is-called-multiple-time – Josh Berry Jul 14 '14 at 22:45
  • @JoshBerry, yep the profile show that the main issue in our code is the cancel/insert of task in the scheduler. I will take a look in 'debouncing'. – Marcos Roriz Junior Jul 14 '14 at 23:14
  • I'm impressed that something like this could be eating your time. What sort of timeframe are we talking here? You might be better off putting a simple test for tolerance in rescheduling. For example, instead of always cancelling and rescheduling, you can make it so that every X interval you just leave it on the currently scheduled task. This really depends on some of the numbers we are talking about, though. – Josh Berry Jul 15 '14 at 01:28
  • 1
    So, yeah, how often are we talking about getting these events? How important is the X seconds after the last event? You could alternatively setup an event that runs in X seconds and checks a flag when it awakens. If it is beyond X, run the task, otherwise schedule for a task to run for the delta. – Josh Berry Jul 15 '14 at 01:30

0 Answers0