0

I am trying to execute a periodic action using Java Concurrency package and I am using the following code:

ScheduledExecutorService daemon = Executors.newScheduledThreadPool(1);
daemon.scheduleWithFixedDelay(new AddressThread(ParentMap.getSingletonInstance(), dictionary, test),10, 10, TimeUnit.SECONDS);

where AddressThread is a Runnable type that is passed. The code executes run() every 10 seconds and it is working as I expect. However, I need to return a value and run() does not let me do that. Is there a similar method like scheduleWithFixedDelay where I can pass a Callable interface rather than a Runnable and return something back? If not, how can I do equivalent stuff like above if I want to return a value?

Dan Smith
  • 423
  • 2
  • 5
  • 17
  • scheduleWithFixedDelay accepts only Runnable as argument, not Callable. Because of that the return type of the ScheduledFuture is null. Only the method schedule accepts both Runnable and Callable. For your case I guess it makes sense to use it. Last but not least, since you are using one single thread in the pool, why don't use .newSingleThreadScheduledExecutor() rather than newScheduledThreadPool(1) ? – Enrico Giurin Feb 07 '17 at 06:25

1 Answers1

0

The problem is where do you want to process the result. If your task is executed once you will get the result of the task from the returned ScheduledFuture (see here: here)

When you have several calls noone is able to distinguish when the return value is available.

You could either implement a Listener and call it at the end of your task, our you have a seperate thread, that waits until the result is available, processes it and then schedules the next execution.

Jens Baitinger
  • 2,230
  • 14
  • 34