Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torgeir/6ae2b9148e4d9961e730ded1fa98400b to your computer and use it in GitHub Desktop.
Save torgeir/6ae2b9148e4d9961e730ded1fa98400b to your computer and use it in GitHub Desktop.
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