Implement
an application such that, it throws an Exception if given block of code runs
longer acceptable.
Using
'Future.get' method, we can solve this problem.
V
get(long timeout, TimeUnit unit)cthrows InterruptedException,
ExecutionException,cTimeoutException
Waits if
necessary for at most the given time for the computation to complete, and then
retrieves its result, if available. It throws, TimeoutException, if the wait
timed out.
Step 1: Create Runnable task.
Runnable
task = new Runnable() {
public void run() {
try {
while (true) {
Thread.sleep(1000);
System.out.println("Hi");
}
} catch (Exception e) {
}
}
};
Step 2: Submit the task to a thread pool.
ExecutorService
executor = Executors.newSingleThreadExecutor();
Future<?>
future = executor.submit(task);
Step 3: Use get method to wait until the task
is finished.
try {
future.get(5, TimeUnit.SECONDS);
} catch
(TimeoutException e) {
System.out.println("Task is taking
more than 5 seconds");
System.out.println("Exiting the
execution of task");
if (!executor.isTerminated())
executor.shutdownNow();
}
As you see
above snippet, I shutdown the executor when the task took more than 5 seconds.
App.java
package com.sample.app; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class App { private static final ExecutorService executor = Executors.newSingleThreadExecutor(); public static void main(String args[]) throws IOException { Runnable task = new Runnable() { public void run() { try { while (true) { Thread.sleep(1000); System.out.println("Hi"); } } catch (Exception e) { } } }; Future<?> future = executor.submit(task); try { future.get(5, TimeUnit.SECONDS); } catch (TimeoutException e) { System.out.println("Task is taking more than 5 seconds"); System.out.println("Exiting the execution of task"); if (!executor.isTerminated()) executor.shutdownNow(); } catch (Exception e) { e.printStackTrace(); } } }
Output
Hi
Hi
Hi
Hi
Task is
taking more than 5 seconds
Exiting
the execution of task
You may
like
No comments:
Post a Comment