Skip to content

Instantly share code, notes, and snippets.

@ansig
Last active August 29, 2015 14:10
Show Gist options
  • Save ansig/1a2096ae9ae282672a5d to your computer and use it in GitHub Desktop.
Save ansig/1a2096ae9ae282672a5d to your computer and use it in GitHub Desktop.
Use a callable object to retrieve values from tasks executed in a thread pool.
import java.util.concurrent.*;
/**
* Use a callable to retrieve values from tasks executed in a thread pool.
*/
public class CallableFuture {
public static void main(String[] args) {
Callable<Long> task = new Factorial(20);
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Long> result = service.submit(task);
String threadName = Thread.currentThread().getName();
System.out.printf("%s waiting for result...%n", threadName);
try {
System.out.printf("%s got result: %d%n", threadName, result.get());
} catch (InterruptedException e) {
System.err.printf("%s interrupted while waiting for result!%n", threadName);
} catch (ExecutionException e) {
System.err.printf("%s got exception while executing task: %s%n", threadName, e.getMessage());
}
service.shutdown();
}
}
class Factorial implements Callable<Long> {
private long n;
public Factorial(long n) {
System.out.printf("%s created callable Factorial with n: %d%n", Thread.currentThread().getName(), n);
this.n = n;
}
@Override
public Long call() throws Exception {
String threadName = Thread.currentThread().getName();
System.out.printf("%s calculating factorial...%n", threadName);
long factorial = 1;
for (long j = 1; j <= n; j++) {
System.out.printf("%s factorial %d*%d=", threadName, factorial, j);
factorial *= j;
System.out.printf("%d%n", factorial);
}
return factorial;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment