Last active
September 28, 2020 03:08
-
-
Save ashishlahoti/cf8ce56d06fdf1ed0600736ba34ed5ce to your computer and use it in GitHub Desktop.
A Task is running in a separate thread. Stop the task if it exceeds 10 minutes
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 com.example.thread; | |
import java.util.concurrent.ExecutionException; | |
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; | |
/** | |
* A Task is running in a separate thread. Stop the task if it exceeds 10 minutes | |
* @author aklahoti | |
*/ | |
public class StopThreadAfterTimeout { | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
usingThreadInterrupt(); | |
//usingThreadPoolShutdownNow(); | |
//usingFutureCancel(); | |
} | |
private static void usingThreadInterrupt() throws InterruptedException { | |
// 1. create a thread | |
Thread t1 = new Thread(() -> { | |
while (!Thread.currentThread().isInterrupted()) { | |
// next step | |
} | |
}); | |
// 2. timeout after 10 minutes | |
Thread.sleep(10 * 60 * 1000); | |
// 3. stop the thread | |
t1.interrupt(); | |
} | |
private static void usingThreadPoolShutdownNow() throws InterruptedException { | |
ExecutorService threadPool = Executors.newFixedThreadPool(2); | |
// 1. create a thread | |
threadPool.submit(() -> { | |
while (!Thread.currentThread().isInterrupted()) { | |
// next step | |
} | |
}); | |
// 2. timeout after 10 minutes | |
Thread.sleep(10 * 60 * 1000); | |
// 3. stop the thread | |
threadPool.shutdownNow(); // internally call thread interrupt | |
} | |
private static void usingFutureCancel() throws InterruptedException, ExecutionException { | |
ExecutorService service = Executors.newFixedThreadPool(2); | |
// 1. submit new callable task which return future object | |
Future<?> future = service.submit(() -> { | |
while (!Thread.currentThread().isInterrupted()) { | |
// next step | |
} | |
}); | |
// 2. wait for 10 minutes to get response | |
try { | |
future.get(10, TimeUnit.MINUTES); | |
} catch (TimeoutException e) { | |
// 3. stop the thread | |
future.cancel(true); // internally call thread interrupt | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment