FutureTask
- Similar to Latch
- implements Future
- has 3 states :
- Waiting to run, Running and Completed
- Once FutureTask completed, it cannot be restarted
- needs Callable in its constructor
- Callable is similar to Runnable used in Thread' s constructor
- Callable implements call method which is used to return the data
- Future.get() returns data [using Callable.call] if ready, otherwise waits for loading data
- Future.get() throws ExecutionException as a wrapper on any exception thrown by task code
- used by the Executor framework
Using FutureTask
1. Defining FutureTask to provide data
// Create new object FutureTask with return type as generic
// Create new Callable object (+ implement call method)
// and pass it to FutureTask constructor
FutureTask future = new FutureTask<UserInfo> (
new Callable<UserInfo>() {
public UserInfo call() throws UserDataException {
return loadData();
}
});
2. Start FutureTask as a thraed
// Define a thread using FutureTask
private Thread thread = new Thread(future);
// Start the thread
public void start() { thread.start(); }
3. Get the data using FutureTask
// Call FutureTask.get to load the data
try {
return future.get();
} catch (ExecutionException e) {
// Hanlde it
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.