Why does Java’s schedulewithfixeddelay use runnable instead of futuretask > Packaging runnable?
Why does Java's schedulewithfixeddelay use runnable instead of futuretask to wrap runnable?
It can be easily displayed using two different code examples:
scheduledexecutorservice executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("beep"); return 1; } }),1,5,TimeUnit.SECONDS);
Production:
But the application didn't quit, it just seemed to wait
However:
scheduledexecutorservice executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { System.out.println("beep "); } },TimeUnit.SECONDS);
Production:
Doodle doodle doodle
At five second intervals
It seems that there are some locks here that I can't be sure of
Solution
Because you're a little abusive of futuretask
According to JavaDocs, futuretask is "cancelable asynchronous computing", but more generally, it includes specific execution of runnable / callable to provide asynchrony I didn't actually realize that it implemented runnable until I just checked the implementation of – run() "set this future as its calculation result"
So what happens in your first example is that you are scheduling future tasks. Its run method is called after 1 second, so it calculates the calculation result (i.e. running the embedded runnable) When this method exits, futuretask is now running and has its concrete results - so the future call to run () is no ops
I think the fundamental problem here is that it seems meaningless to directly arrange futuretask, at least not the way you do it here If you want to run some code every five seconds, you should definitely use the second method Futuretask embodies (single!) calculation; You have no reason to call it multiple times. In fact, it caches the results to prevent this