Advertisement
Guest User

Untitled

a guest
Mar 10th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. public class FutureCancel {
  2.     public static void main(String[] args) throws InterruptedException, ExecutionException {
  3.         ExecutorService executorService = Executors.newSingleThreadExecutor();
  4.  
  5.         TestSync s1 = new TestSync();
  6.         TestSync s2 = new TestSync();
  7.         Callable<String> callable = () -> {
  8.             // Perform some computation
  9.             for (int i = 0; i < 5; i++) {
  10.                 s1.increment();
  11.                 s2.increment();
  12.             }
  13.             System.out.println("Result: " + s1.getValue());
  14.             System.out.println("Result: " + s2.getValue());
  15.             Thread.sleep(1000);
  16.             return "Hello from Callable";
  17.         };
  18.         long startTime = System.nanoTime();
  19.         Future<String> future = executorService.submit(callable);
  20.  
  21.         while(!future.isDone()) {
  22.             System.out.println("Task is still not done...");
  23.             Thread.sleep(200);
  24.             double elapsedTimeInSec = (System.nanoTime() - startTime) / 1000000000.0;
  25.  
  26.             if (elapsedTimeInSec > 1) {
  27.                 // cancel future if the elapsed time is more than one second
  28.                 future.cancel(true);
  29.             }
  30.         }
  31.  
  32.         // Check if future is cancelled before retrieving the result
  33.         if(!future.isCancelled()) {
  34.             System.out.println("Task completed! Retrieving the result");
  35.             // Future.get() blocks until the result is available
  36.             String result = future.get();
  37.             System.out.println(result);
  38.         } else {
  39.             System.out.println("Task was cancelled");
  40.         }
  41.  
  42.         executorService.shutdown();
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement