I have a scenario where I have to poll the remote server, checking if the task is completed. After that, I make another call to get the result.
I originally intended to use SingleThreadScheduledExecutor with scheduleWithFixedDelay to poll:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture future = executor.scheduleWithFixedDelay(() -> poll(jobId), 0, 10, TimeUnit.SECONDS); public void poll(String jobId) { boolean jobDone = remoteServer.isJobDone(jobId); if (jobDone) { retrieveJobResult(jobId); } }
But since I can only provide Runnable to scheduleWithFixedDelay , which cannot return anything, I do not understand when the future will be completed, if ever. What does calling future.get() mean? What result am I waiting for?
When I start the remote task for the first time, I want to make another remote call and set its result as the future value. I suggested that I could use CompletableFuture to do this to forward my poll method, which in turn redirects it to my retrieveTask method, which ultimately completes it:
CompletableFuture<Object> result = new CompletableFuture<Object>(); ScheduledFuture future = executor.scheduleWithFixedDelay(() -> poll(jobId, result), 0, 10, TimeUnit.SECONDS); public void poll(String jobId, CompletableFuture<Object> result) { boolean jobDone = remoteServer.isJobDone(jobId); if (jobDone) { retrieveJobResult(jobId, result); } } public void retrieveJobResult(String jobId, CompletableFuture<Object> result) { Object remoteResult = remoteServer.getJobResult(jobId); result.complete(remoteResult); }
But this has a lot of problems. For example, CompletableFuture is not even intended for such use. Instead, I had to do CompletableFuture.supplyAsync(() -> poll(jobId)) , I think, but how would I then correctly turn off the executor and cancel the future , which was returned when my CompletableFuture canceled / completed? It seems that the survey should be implemented in a completely different way.