From 082758c1be3b8624ce529d1c4fa8afa976781bb3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 21 Feb 2020 16:24:12 +0100 Subject: [PATCH] [New] Added ExecutorPool for easier ExecutorService pool management --- .../java/li/strolch/utils/ExecutorPool.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 li.strolch.utils/src/main/java/li/strolch/utils/ExecutorPool.java diff --git a/li.strolch.utils/src/main/java/li/strolch/utils/ExecutorPool.java b/li.strolch.utils/src/main/java/li/strolch/utils/ExecutorPool.java new file mode 100644 index 000000000..a7e3fa405 --- /dev/null +++ b/li.strolch.utils/src/main/java/li/strolch/utils/ExecutorPool.java @@ -0,0 +1,61 @@ +package li.strolch.utils; + +import static java.util.concurrent.Executors.*; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import li.strolch.utils.dbc.DBC; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExecutorPool { + + private static final Logger logger = LoggerFactory.getLogger(ExecutorPool.class); + + private Map executors; + + public ExecutorPool() { + this.executors = Collections.synchronizedMap(new HashMap<>()); + } + + public ExecutorService getExecutor(String poolName) { + DBC.PRE.assertNotEmpty("poolName must be set!", poolName); + return this.executors.computeIfAbsent(poolName, p -> newCachedThreadPool(new NamedThreadPoolFactory(p))); + } + + public ExecutorService getSingleThreadExecutor(String poolName) { + DBC.PRE.assertNotEmpty("poolName must be set!", poolName); + return this.executors.computeIfAbsent(poolName, p -> newSingleThreadExecutor(new NamedThreadPoolFactory(p))); + } + + public ScheduledExecutorService getScheduledExecutor(String poolName) { + DBC.PRE.assertNotEmpty("poolName must be set!", poolName); + return (ScheduledExecutorService) this.executors + .computeIfAbsent(poolName, p -> newScheduledThreadPool(4, new NamedThreadPoolFactory(p))); + } + + public void destroy() { + + for (String poolName : this.executors.keySet()) { + logger.info("Shutting down executor pool " + poolName); + ExecutorService executor = this.executors.get(poolName); + + try { + executor.shutdown(); + executor.awaitTermination(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + logger.error("Was interrupted while shutting down tasks"); + } finally { + if (!executor.isTerminated()) { + logger.error("Tasks not stopped after " + 5 + "s. Shutting down now."); + executor.shutdownNow(); + } + } + } + } +}