Example of FutureTask in Java
December 23, 2012
java.util.concurrent.FutureTask has been introduced in JDK 5 and is the part of executor framework. FutureTask has method cancel that allow canceling the task. It implements the Future interface. FutureTask object is created by passing the object of the class which implements Callable. And if before calling the run method, task is cancelled then on calling run method of future task, will not allow running the thread. Find the example.
FutureTaskTest.java
package com.concretepage; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class FutureTaskTest { public static void main(String... args){ FutureTask<String> ft= new FutureTask<String>(new DemoTask()); boolean b=ft.cancel(true); ft.run(); System.out.println(b); } } class DemoTask implements Callable<String>{ public String call() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(e); } return "Task Done"; } }
Find another example that completes its task and uses different method of FutureTask to check the task health.
FutureTaskDemo.java
package com.concretepage; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; public class FutureTaskDemo { public static void main(String... args) throws InterruptedException, ExecutionException{ ExecutorService exService = Executors.newSingleThreadExecutor(); FutureTask<String> futureTask= new FutureTask<String>(new Task()); exService.execute(futureTask); //checks if task done System.out.println(futureTask.isDone()); //checks if task canceled System.out.println(futureTask.isCancelled()); //fetches result and waits if not ready System.out.println(futureTask.get()); } } class Task implements Callable<String>{ public String call() { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(e); } return "Task Done"; } }
false false Task Done