fork download
  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.Future;
  6.  
  7.  
  8. class ProcessingChainElement implements Callable<String> {
  9. private final Future<String> previous;
  10. public ProcessingChainElement(Future<String> previousResult) {
  11. previous = previousResult;
  12. }
  13. @Override
  14. public String call() throws Exception {
  15. // prepare something that may take some time..
  16. Thread.sleep(500);
  17. String result;
  18. if (previous != null) {
  19. result = previous.get() + " [" + System.currentTimeMillis() + "]";
  20. } else {
  21. result = "[" + System.currentTimeMillis() + "]";
  22. }
  23. return result;
  24. }
  25. }
  26.  
  27. public class Main {
  28.  
  29. public static void main(String[] args) throws InterruptedException, ExecutionException {
  30. long start = System.currentTimeMillis();
  31.  
  32. ExecutorService executor = Executors.newFixedThreadPool(3);
  33. Future<String> result1 = executor.submit(new ProcessingChainElement(null));
  34. Future<String> result2 = executor.submit(new ProcessingChainElement(result1));
  35. Future<String> result3 = executor.submit(new ProcessingChainElement(result2));
  36. executor.shutdown();
  37.  
  38. logTime("submitting", start);
  39.  
  40. start = System.currentTimeMillis();
  41. String result = result3.get();
  42. logTime("getting result", start);
  43.  
  44. System.out.println("Result is: " + result);
  45. }
  46.  
  47. private static void logTime(String what, long start) {
  48. long end = System.currentTimeMillis();
  49. long diff = end - start;
  50. System.out.printf("[%s] took %4d ms%n", what, diff);
  51. }
  52. }
  53.  
Success #stdin #stdout 0.08s 382336KB
stdin
Standard input is empty
stdout
[submitting] took    4 ms
[getting result] took  495 ms
Result is: [1375710427753] [1375710427753] [1375710427754]