Last active
October 12, 2017 12:55
-
-
Save torgeir/6ae2b9148e4d9961e730ded1fa98400b to your computer and use it in GitHub Desktop.
Check for running tasks in ThreadPoolExecutor java
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
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