Java's java.util.concurrent.CompletionService
is a powerful tool for managing asynchronous tasks. It allows you to submit tasks and track their progress, receive notifications when tasks complete, and even cancel tasks if necessary.
Here's a simple example of how to use CompletionService
to submit a task and track its progress:
// Create a CompletionService
CompletionService<String> service = new ExecutorCompletionService<>(executor);
// Submit a task
Future<String> future = service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// Do some work
return "Result";
}
});
// Track the task's progress
while (!future.isDone()) {
// Do something else
}
// Get the task's result
String result = future.get();
As you can see, CompletionService
makes it easy to submit and track the progress of asynchronous tasks. It also provides convenient methods for receiving notifications when tasks complete and for cancelling tasks if necessary.
External resources: