Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check for running tasks in ThreadPoolExecutor java
public class CalculationExecutor {
private final ThreadPoolExecutor executor;
public CalculationExecutor() {
executor = createThreadPool(1);
}
public void execute(Runnable runnable) {
executor.execute(runnable);
}
public boolean hasRunningCalculations() {
return executor.getActiveCount() > 0;
}
private static ThreadPoolExecutor createThreadPool(int threads) {
return new ThreadPoolExecutor(threads, threads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
}
public static void main(String[] args) throws InterruptedException {
CalculationExecutor calculationExecutor = new CalculationExecutor();
System.out.println(calculationExecutor.hasRunningCalculations()); // false
calculationExecutor.execute(() -> {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
System.out.println(calculationExecutor.hasRunningCalculations()); // true
Thread.sleep(101);
System.out.println(calculationExecutor.hasRunningCalculations()); // false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.