Steps of using FutureTask
1. Define FutureTask and Callable implementation
2. Provide Callable object in FutureTask constructor
3. Create a thread and provide FutureTask object in its constructor
4. Start the thread
5. Use FutureTask using FutureTask.get() to get the data
6. Handle ExecutionException
Example
public class DataLoader {
// 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();
}
});
// Define a thread using FutureTask
private Thread thread = new Thread(future);
// Start the thread
public void start() { thread.start(); }
public UserInfo getData() throws UserDataException, ExecutionException {
// Call FutureTask.get to load the data and handle ExecutionException
try {
return future.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof UserDataException)
throw (UserDataException) cause;
else
throw e; }
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.