2

How can I use the Java concurrency API to get a reference to the task that is scheduled for execution?

I can do something like this, and keep the reference to myRunnable:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
SimpleRunnable myRunnable = new SimpleRunnable();
exec.scheduleAtFixedRate(myRunnable, 0, 2, TimeUnit.SECONDS);

But is there a way to use the Executor service or ScheduledFuture to get the reference?

This question shows a collection of Future objects and discusses that they keep a reference to the task, but I don't see any public API method exposing it.

Community
  • 1
  • 1
sjgp
  • 310
  • 5
  • 17

1 Answers1

0

The future reference represents the computation result of the asynchronous task while the task itself is basically the runnable reference that you pass to the scheduleAtFixedRate method ('myRunnable' in the below example).

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
SimpleRunnable myRunnable = new SimpleRunnable();
ScheduledFuture<?> future  = exec.scheduleAtFixedRate(myRunnable, 0, 2, 
TimeUnit.SECONDS);

I don't think you have a way to retrieve the Runnable from the executor itself. Please elaborate what you are willing to achieve and I'll try to assist you.

Itzik Shachar
  • 744
  • 5
  • 16
  • Yes, I could hang onto the reference for the ScheduledFuture object, but I still do not see any way of getting a reference to the task. – sjgp Apr 26 '17 at 16:18
  • I don't think you have a way to retrieve the Runnable from the executor itself. Please elaborate what you are willing to achieve and I'll try to assist you. – Itzik Shachar Apr 26 '17 at 16:48
  • I am exploring design options for a requirement that a task be run at regular intervals to do some work, and gather information as it does. A second, independent process needs access to that information. Access does not need to be via Executor or Future API, and I can design another solution since referencing the Task that way does not appear to be an option. Thanks for your thoughts! – sjgp Apr 26 '17 at 17:27
  • First, you need to wait for the first thread to finish execution before the second thread can access the result and work with it. You don't need an access to the task, you need an access to the execution result. I invite you to explore this link: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html to see if it fits your needs. If not, please post a comment here again for further assistance. – Itzik Shachar Apr 27 '17 at 08:32