Created
March 14, 2017 13:47
-
-
Save rozaydin/8477421b40317e4d24a27a28e9e53710 to your computer and use it in GitHub Desktop.
Future<T> get() with timeout scenario - Task does not complete within defined timeout duration - TimeoutException occurs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.tutorial.future; | |
import org.tutorial.future.task.FibonacciTask; | |
import java.util.concurrent.*; | |
/** | |
* Created by rozaydin on 3/14/17. | |
*/ | |
public class GetTimeoutScenario2 { | |
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); | |
/** | |
* Executes the task and calls get(1l, TimeUnit.MILISECONDS) | |
* this method will wait for 1 mili seconds at most for the task | |
* to complete, if task completed before 10 seconds gets the result and prints it | |
* otherwise throws a TimeoutException - For this scenario we expect a TimeoutException | |
* to occur | |
*/ | |
public void execute() { | |
Future<Long> result = singleThreadExecutor.submit(() -> FibonacciTask.calculate(40)); // 30 - 832040 | |
singleThreadExecutor.shutdown(); | |
// 1. get result | |
try { | |
// | |
System.out.println("1. calling Future.get() -- this method will block"); | |
long fiboNumber = result.get(1l, TimeUnit.MILLISECONDS); | |
System.out.println("Fibonacci Number is: " + fiboNumber ); | |
} catch (InterruptedException ie) { | |
Thread.currentThread().interrupt(); | |
System.out.println("Task interrupted! " + ie); | |
} catch (ExecutionException ee) { | |
System.out.println("Execution exception occured! " + ee); | |
} catch (TimeoutException te) { | |
System.out.println("Timeout Execution exception occured! " + te); | |
} | |
} | |
public static void main(String[] args) { | |
GetTimeoutScenario2 scenario = new GetTimeoutScenario2(); | |
scenario.execute(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment