diff --git a/pom.xml b/pom.xml index d0409e7..d9463af 100644 --- a/pom.xml +++ b/pom.xml @@ -43,6 +43,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -126,26 +134,6 @@ - - skip-pre-jdk8 - - (,1.8) - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/jdk8/** - - - - - - - run-sample diff --git a/src/main/java/org/ice4j/stack/Connector.java b/src/main/java/org/ice4j/stack/Connector.java index 8e404f7..9b979f6 100644 --- a/src/main/java/org/ice4j/stack/Connector.java +++ b/src/main/java/org/ice4j/stack/Connector.java @@ -20,7 +20,7 @@ package org.ice4j.stack; import java.io.*; import java.net.*; import java.nio.channels.*; -import java.util.concurrent.*; +import java.util.function.*; import java.util.logging.*; import org.ice4j.*; @@ -29,8 +29,9 @@ import org.ice4j.socket.*; /** * The Network Access Point is the most outward part of the stack. It is * constructed around a datagram socket and takes care of forwarding incoming - * messages to the MessageProcessor as well as sending datagrams to the STUN - * server specified by the original NetAccessPointDescriptor. + * messages to the provided {@link #messageConsumer} as well as sending + * datagrams to the STUN server specified by the + * original NetAccessPointDescriptor. * * @author Emil Ivov */ @@ -44,9 +45,9 @@ class Connector = Logger.getLogger(Connector.class.getName()); /** - * The message queue is where incoming messages are added. + * The consumer of incoming RawMessages */ - private final BlockingQueue messageQueue; + private final Consumer messageConsumer; /** * The socket object that used by this access point to access the network. @@ -87,16 +88,16 @@ class Connector * communication. * @param remoteAddress the remote address of the socket of this * {@link Connector} if it is a TCP socket, or null if it is UDP. - * @param messageQueue the Queue where incoming messages should be queued + * @param messageConsumer the incoming messages consumer * @param errorHandler the instance to notify when errors occur. */ protected Connector(IceSocketWrapper socket, TransportAddress remoteAddress, - BlockingQueue messageQueue, + Consumer messageConsumer, ErrorHandler errorHandler) { this.sock = socket; - this.messageQueue = messageQueue; + this.messageConsumer = messageConsumer; this.errorHandler = errorHandler; this.remoteAddress = remoteAddress; @@ -230,7 +231,7 @@ class Connector listenAddress.getTransport()), listenAddress); - messageQueue.add(rawMessage); + messageConsumer.accept(rawMessage); } catch (SocketException ex) { diff --git a/src/main/java/org/ice4j/stack/MessageProcessingTask.java b/src/main/java/org/ice4j/stack/MessageProcessingTask.java new file mode 100644 index 0000000..4da5799 --- /dev/null +++ b/src/main/java/org/ice4j/stack/MessageProcessingTask.java @@ -0,0 +1,216 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.stack; + +import java.util.concurrent.atomic.*; +import java.util.function.*; +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.message.*; + +/** + * The class is used to parse and dispatch incoming messages by being + * executed by concurrent {@link java.util.concurrent.ExecutorService}. + * To reduce memory allocation this class is designed to be suitable for + * usage with pooling, the instance of this type is mutable such that + * RawMessage can be updated and instance can be reused and + * scheduled with new RawMessage + * + * @author Emil Ivov + * @author Yura Yaroshevich + */ +class MessageProcessingTask + implements Runnable +{ + /** + * Our class logger. + */ + private static final Logger logger + = Logger.getLogger(MessageProcessingTask.class.getName()); + + /** + * Indicates that MessageProcessingTask is cancelled and should not + * process RawMessage anymore. + */ + private final AtomicBoolean cancelled = new AtomicBoolean(false); + + /** + * The NetAccessManager which has created this instance and which + * is its owner. + */ + private final NetAccessManager netAccessManager; + + /** + * The listener that will be collecting error notifications. + */ + private final ErrorHandler errorHandler; + + /** + * The listener that will be retrieving MessageEvents + */ + private final MessageEventHandler messageEventHandler; + + /** + * Raw message which is being processed + */ + private RawMessage rawMessage; + + /** + * Callback which is invoked when this MessageProcessingTask + * processed it's {@link #rawMessage} + */ + private Consumer rawMessageProcessedHandler; + + /** + * Creates a Message processor. + * + * @param netAccessManager the NetAccessManager which is creating + * the new instance, is going to be its owner, specifies the + * MessageEventHandler and represents the ErrorHandler to + * handle exceptions in the new instance + * @throws IllegalArgumentException if any of the mentioned properties of + * netAccessManager are null + */ + MessageProcessingTask(NetAccessManager netAccessManager) + throws IllegalArgumentException + { + if (netAccessManager == null) + { + throw new NullPointerException("netAccessManager"); + } + + MessageEventHandler messageEventHandler + = netAccessManager.getMessageEventHandler(); + + if (messageEventHandler == null) + { + throw new IllegalArgumentException( + "The message event handler may not be null"); + } + + this.netAccessManager = netAccessManager; + this.messageEventHandler = messageEventHandler; + this.errorHandler = netAccessManager; + } + + /** + * Assigns the RawMessage that will be processed + * by this MessageProcessingTask on executor's thread. + * @param message RawMessage to be processed + * @param onProcessed callback which will be invoked when processing + * of {@link #rawMessage} is completed + */ + void setMessage( + RawMessage message, + Consumer onProcessed) + { + if (message == null) + { + throw new IllegalArgumentException("The message may not be null"); + } + rawMessage = message; + rawMessageProcessedHandler = onProcessed; + } + + /** + * Performs proper reset of internal state of pooled instance. + */ + void resetState() + { + cancelled.set(false); + rawMessage = null; + rawMessageProcessedHandler = null; + } + + /** + * Attempts to cancel processing of {@link #rawMessage} + */ + public void cancel() + { + cancelled.set(true); + } + + /** + * Does the message parsing. + */ + @Override + public void run() + { + final Consumer onProcessed + = rawMessageProcessedHandler; + final RawMessage message = rawMessage; + //add an extra try/catch block that handles uncatched errors + try + { + if (message == null) + { + return; + } + rawMessage = null; + rawMessageProcessedHandler = null; + + if (cancelled.get()) + { + return; + } + + StunStack stunStack = netAccessManager.getStunStack(); + + Message stunMessage; + try + { + stunMessage + = Message.decode(message.getBytes(), + (char) 0, + (char) message.getMessageLength()); + } + catch (StunException ex) + { + errorHandler.handleError( + "Failed to decode a stun message!", + ex); + return; + } + + logger.finest("Dispatching a StunMessageEvent."); + + StunMessageEvent stunMessageEvent + = new StunMessageEvent(stunStack, message, stunMessage); + + messageEventHandler.handleMessageEvent(stunMessageEvent); + } + catch (Throwable err) + { + errorHandler.handleFatalError( + Thread.currentThread(), + "Unexpected Error!", err); + } + finally + { + // On processed callback must be invoked in all cases, even when + // cancellation or early exist happen, otherwise + // NetAccessManager internal tracking of pooled and active + // message processors will missbehave. + if (onProcessed != null) + { + onProcessed.accept(this); + } + } + } +} diff --git a/src/main/java/org/ice4j/stack/MessageProcessor.java b/src/main/java/org/ice4j/stack/MessageProcessor.java deleted file mode 100644 index a1d2da1..0000000 --- a/src/main/java/org/ice4j/stack/MessageProcessor.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 Atlassian Pty Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.ice4j.stack; - -import java.util.concurrent.*; -import java.util.logging.*; - -import org.ice4j.*; -import org.ice4j.message.*; - -/** - * The class is used to parse and dispatch incoming messages in a multi-thread - * manner. - * - * @author Emil Ivov - */ -class MessageProcessor - implements Runnable -{ - /** - * Our class logger. - */ - private static final Logger logger - = Logger.getLogger(MessageProcessor.class.getName()); - - /** - * The listener that will be collecting error notifications. - */ - private final ErrorHandler errorHandler; - - /** - * The queue where we store incoming messages until they are collected. - */ - private final BlockingQueue messageQueue; - - /** - * The listener that will be retrieving MessageEvents - */ - private final MessageEventHandler messageEventHandler; - - /** - * The NetAccessManager which has created this instance and which - * is its owner. - */ - private final NetAccessManager netAccessManager; - - /** - * The flag that indicates whether we are still running. - */ - private boolean running = false; - - /** - * A reference to the thread that we use to execute ourselves. - */ - private Thread runningThread = null; - - /** - * Creates a Message processor. - * - * @param netAccessManager the NetAccessManager which is creating - * the new instance, is going to be its owner, specifies the - * BlockingQueue which is to store incoming messages, specifies the - * MessageEventHandler and represents the ErrorHandler to - * handle exceptions in the new instance - * @throws IllegalArgumentException if any of the mentioned properties of - * netAccessManager are null - */ - MessageProcessor(NetAccessManager netAccessManager) - throws IllegalArgumentException - { - if (netAccessManager == null) - throw new NullPointerException("netAccessManager"); - - BlockingQueue messageQueue = netAccessManager.getMessageQueue(); - - if (messageQueue == null) - { - throw new IllegalArgumentException( - "The message queue may not be null"); - } - - MessageEventHandler messageEventHandler - = netAccessManager.getMessageEventHandler(); - - if(messageEventHandler == null) - { - throw new IllegalArgumentException( - "The message event handler may not be null"); - } - - this.netAccessManager = netAccessManager; - this.messageQueue = messageQueue; - this.messageEventHandler = messageEventHandler; - this.errorHandler = netAccessManager; - } - - /** - * Does the message parsing. - */ - public void run() - { - //add an extra try/catch block that handles uncatched errors and helps - //avoid having dead threads in our pools. - try - { - StunStack stunStack = netAccessManager.getStunStack(); - - while (running) - { - RawMessage rawMessage; - - try - { - rawMessage = messageQueue.take(); - } - catch (InterruptedException ex) - { - if(isRunning()) - logger.log(Level.WARNING, - "A net access point has gone useless: ", ex); - //nothing to do here since we test whether we are running - //just beneath ... - rawMessage = null; - } - - // were we asked to stop? - if (!isRunning()) - return; - //anything to parse? - if (rawMessage == null) - continue; - - Message stunMessage = null; - try - { - stunMessage - = Message.decode(rawMessage.getBytes(), - (char) 0, - (char) rawMessage.getMessageLength()); - } - catch (StunException ex) - { - errorHandler.handleError( - "Failed to decode a stun message!", - ex); - - continue; //let this one go and for better luck next time. - } - - logger.finest("Dispatching a StunMessageEvent."); - - StunMessageEvent stunMessageEvent - = new StunMessageEvent(stunStack, rawMessage, - stunMessage); - - messageEventHandler.handleMessageEvent(stunMessageEvent); - } - } - catch(Throwable err) - { - //notify and bail - errorHandler.handleFatalError(this, "Unexpected Error!", err); - } - } - - /** - * Start the message processing thread. - */ - void start() - { - this.running = true; - - runningThread = new Thread(this, "Stun4J Message Processor"); - runningThread.setDaemon(true); - runningThread.start(); - } - - /** - * Shut down the message processor. - */ - void stop() - { - this.running = false; - runningThread.interrupt(); - } - - /** - * Determines whether the processor is still running; - * - * @return true if the processor is still authorized to run, and false - * otherwise. - */ - boolean isRunning() - { - return running; - } -} diff --git a/src/main/java/org/ice4j/stack/NetAccessManager.java b/src/main/java/org/ice4j/stack/NetAccessManager.java index 2d8a45d..2c356b9 100644 --- a/src/main/java/org/ice4j/stack/NetAccessManager.java +++ b/src/main/java/org/ice4j/stack/NetAccessManager.java @@ -21,22 +21,27 @@ import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; +import java.util.concurrent.atomic.*; +import java.util.function.*; import java.util.logging.*; +import java.util.logging.Logger; // Disambiguation import org.ice4j.*; import org.ice4j.message.*; import org.ice4j.socket.*; +import org.ice4j.util.*; /** - * Manages Connectors and MessageProcessor pooling. This class - * serves as a layer that masks network primitives and provides equivalent STUN - * abstractions. Instances that operate with the NetAccessManager are only - * supposed to understand STUN talk and shouldn't be aware of datagrams sockets, - * and etc. + * Manages Connectors and MessageProcessingTask execution and + * pooling. This class serves as a layer that masks network primitives and + * provides equivalent STUN abstractions. Instances that operate with + * the NetAccessManager are only supposed to understand STUN talk and + * shouldn't be aware of datagrams sockets, and etc. * * @author Emil Ivov * @author Aakash Garg * @author Boris Grozev + * @author Yura Yaroshevich */ class NetAccessManager implements ErrorHandler @@ -47,6 +52,37 @@ class NetAccessManager private static final Logger logger = Logger.getLogger(NetAccessManager.class.getName()); + /** + * Thread pool to execute {@link MessageProcessingTask}s across all + * {@link NetAccessManager}s. + */ + private static ExecutorService messageProcessingExecutor + = ExecutorFactory.createFixedThreadPool( + Runtime.getRuntime().availableProcessors(), + "ice4j.NetAccessManager-"); + + /** + * Maximum number of {@link MessageProcessingTask} to keep in object pool. + * Each {@link NetAccessManager} has it's own pool, small pool size is + * enough to save allocations. + */ + private static final int TASK_POOL_SIZE = 8; + + /** + * Pool of MessageProcessingTask objects to avoid extra-allocations + * of processor object per RawMessage needed to process. + */ + private final ArrayBlockingQueue taskPool + = new ArrayBlockingQueue<>(TASK_POOL_SIZE); + + /** + * The set of {@link MessageProcessingTask}'s which are not yet finished + * it's, processing, tracking of active tasks is necessary to properly + * cancel pending tasks in case {@link #stop()} is called. + */ + private final ConcurrentHashMap.KeySetView + activeTasks = ConcurrentHashMap.newKeySet(); + /** * All Connectors currently in use with UDP. The table maps a local * TransportAddress and and a remote TransportAddress to @@ -77,16 +113,6 @@ class NetAccessManager tcpConnectors = new HashMap<>(); - /** - * A synchronized FIFO where incoming messages are stocked for processing. - */ - private final BlockingQueue messageQueue = new LinkedBlockingQueue<>(); - - /** - * A thread pool of message processors. - */ - private final Vector messageProcessors = new Vector<>(); - /** * The instance that should be notified when an incoming message has been * processed and ready for delivery @@ -105,17 +131,49 @@ class NetAccessManager */ private final ChannelDataEventHandler channelDataEventHandler; - /** - * The size of the thread pool to start with. - */ - private int initialThreadPoolSize = StunStack.DEFAULT_THREAD_POOL_SIZE; - /** * The StunStack which has created this instance, is its owner and * is the handler that incoming message requests should be passed to. */ private final StunStack stunStack; + /** + * Indicates if this NetAccessManager is stopped + */ + private final AtomicBoolean isStopped = new AtomicBoolean(false); + + /** + * Optionally enabled QueueStatistics to keep track throughput + * of processing {@link MessageProcessingTask} + */ + private final QueueStatistics queueStatistics + = logger.isLoggable(Level.FINEST) + ? new QueueStatistics(this.toString()) + : null; + + /** + * Callback to be called when scheduled MessageProcessingTask + * completes processing it's RawMessage. + */ + private final Consumer onRawMessageProcessed + = messageProcessingTask -> { + + activeTasks.remove(messageProcessingTask); + + if (queueStatistics != null) + { + queueStatistics.remove(System.currentTimeMillis()); + } + + final boolean isAdded = taskPool.offer(messageProcessingTask); + if (!isAdded && logger.isLoggable(Level.FINEST)) + { + logger.finest("Dropping MessageProcessingTask for " + + this + " because pool is full, max pool size is " + + String.valueOf(TASK_POOL_SIZE)); + } + }; + /** * Constructs a NetAccessManager. * @@ -150,7 +208,6 @@ class NetAccessManager this.messageEventHandler = stunStack; this.peerUdpMessageEventHandler = peerUdpMessageEventHandler; this.channelDataEventHandler = channelDataEventHandler; - initThreadPool(); } /** @@ -196,17 +253,6 @@ class NetAccessManager return channelDataEventHandler; } - /** - * Gets the BlockingQueue of this NetAccessManager in which - * incoming messages are stocked for processing. - * - * @return the BlockingQueue of this NetAccessManager in - * which incoming messages are stocked for processing - */ - BlockingQueue getMessageQueue() - { - return messageQueue; - } /** * Gets the StunStack which has created this instance and is its @@ -228,6 +274,12 @@ class NetAccessManager @Override public void handleError(String message, Throwable error) { + if (isStopped.get()) + { + logger.log(Level.WARNING, + "Got error when stopped, ignoring: " + message, error); + return; + } /** * apart from logging, i am not sure what else we could do here. */ @@ -249,6 +301,13 @@ class NetAccessManager String message, Throwable error) { + if (isStopped.get()) + { + logger.log(Level.WARNING, + "Got fatal error when stopped, ignoring: " + message, error); + return; + } + if (callingThread instanceof Connector) { Connector connector = (Connector)callingThread; @@ -265,20 +324,9 @@ class NetAccessManager logger.fine("Removing connector " + connector); } } - else if( callingThread instanceof MessageProcessor ) + else { - MessageProcessor mp = (MessageProcessor)callingThread; - logger.log( Level.WARNING, "A message processor has unexpectedly " - + "stopped. AP:" + mp, error); - - //make sure the guy's dead. - mp.stop(); - messageProcessors.remove(mp); - - mp = new MessageProcessor(this); - mp.start(); - logger.fine("A message processor has been relaunched because " - + "of an error."); + logger.log(Level.SEVERE, message, error); } } @@ -349,7 +397,11 @@ class NetAccessManager if (!connectorsForLocalAddress.containsKey(remoteAddress)) { Connector connector - = new Connector(socket, remoteAddress, messageQueue, this); + = new Connector( + socket, + remoteAddress, + this::onIncomingRawMessage, + this); connectorsForLocalAddress.put(remoteAddress, connector); connector.start(); @@ -405,15 +457,24 @@ class NetAccessManager } /** - * Stops NetAccessManager and all of its MessageProcessor. + * Stops NetAccessManager and all of its active + * MessageProcessingTask. */ @SuppressWarnings("unchecked") public void stop() { - for(MessageProcessor mp : messageProcessors) + // Mark NetAccessManager as stopped, it will immediately result in + // ignoring of all concurrent requests to handle messages + isStopped.set(true); + + // no item can be added to {@link #activeTasks} when + // NetAccessManager is stopped, so it is safe to iterate without + // removing item in-place. + for (MessageProcessingTask messageProcessingTask : activeTasks) { - mp.stop(); + messageProcessingTask.cancel(); } + activeTasks.clear(); for (Object o : new Object[]{udpConnectors, tcpConnectors}) { @@ -475,81 +536,47 @@ class NetAccessManager return connector; } - //---------------thread pool implementation -------------------------------- /** - * Adjusts the number of concurrently running MessageProcessors. - * If the number is smaller or bigger than the number of threads - * currently running, then message processors are created/deleted so that - * their count matches the new value. - * - * @param threadPoolSize the number of MessageProcessors that should be - * running concurrently - * @throws IllegalArgumentException if threadPoolSize is not a valid size. + * Enqueues incoming {@link RawMessage} for asynchronous + * processing by {@link #messageProcessingExecutor} + * @param message RawMessage to process */ - void setThreadPoolSize(int threadPoolSize) - throws IllegalArgumentException + private void onIncomingRawMessage(final RawMessage message) { - if(threadPoolSize < 1) + if (isStopped.get()) { - throw new IllegalArgumentException( - threadPoolSize + " is not a legal thread pool size value."); + logger.fine("Got RawMessage when stopped, ignore it."); + return; } - //if we are not running just record the size - //so that we could init later. - if(messageProcessors.size() < threadPoolSize) + MessageProcessingTask messageProcessingTask + = taskPool.poll(); + if (messageProcessingTask == null) { - //create additional processors - fillUpThreadPool(threadPoolSize); + messageProcessingTask + = new MessageProcessingTask(this); + if (logger.isLoggable(Level.FINEST)) + { + logger.finest("Allocated new MessageProcessingTask for " + + this + " due to absence of available pooled instances"); + } } else { - //delete extra processors - shrinkThreadPool(threadPoolSize); + messageProcessingTask.resetState(); } - } - /** - * Fills the thread pool with the initially specified number of message - * processors. - */ - private void initThreadPool() - { - //create additional processors - fillUpThreadPool(initialThreadPoolSize); - } + messageProcessingTask.setMessage(message, onRawMessageProcessed); - /** - * Starts all message processors - * - * @param newSize the new thread pool size - */ - private void fillUpThreadPool(int newSize) - { - //make sure we don't resize more than once - messageProcessors.ensureCapacity(newSize); + activeTasks.add(messageProcessingTask); - for (int i = messageProcessors.size(); i < newSize; i++) + if (queueStatistics != null) { - MessageProcessor mp = new MessageProcessor(this); - - messageProcessors.add(mp); - mp.start(); - } - } - - /** - * Stops message processors until processors count equals newSize. - * - * @param newSize the new thread pool size - */ - private void shrinkThreadPool(int newSize) - { - while(messageProcessors.size() > newSize) - { - MessageProcessor mp = messageProcessors.remove(0); - mp.stop(); + queueStatistics.add(System.currentTimeMillis()); } + // Use overload which does not return Future object to avoid + // unnecessary allocation + messageProcessingExecutor.execute(messageProcessingTask); } //--------------- SENDING MESSAGES ----------------------------------------- diff --git a/src/main/java/org/ice4j/stack/StunStack.java b/src/main/java/org/ice4j/stack/StunStack.java index ebcda4a..cd29741 100644 --- a/src/main/java/org/ice4j/stack/StunStack.java +++ b/src/main/java/org/ice4j/stack/StunStack.java @@ -44,12 +44,6 @@ import org.ice4j.util.*; public class StunStack implements MessageEventHandler { - - /** - * The number of threads to split our flow in. - */ - public static final int DEFAULT_THREAD_POOL_SIZE = 3; - /** * The Logger used by the StunStack class and its * instances for logging output. @@ -119,18 +113,6 @@ public class StunStack */ private static PacketLogger packetLogger; - /** - * Sets the number of Message processors running in the same time. - * - * @param threadPoolSize the number of message process threads to run. - * @throws IllegalArgumentException if threadPoolSize is not a valid size. - */ - public void setThreadPoolSize(int threadPoolSize) - throws IllegalArgumentException - { - netAccessManager.setThreadPoolSize(threadPoolSize); - } - /** * Creates and starts a Network Access Point (Connector) based on the * specified socket. @@ -960,10 +942,7 @@ public class StunStack ev.getLocalAddress(), ev.getRemoteAddress()); - // if there is an OOM error here, it will lead to - // NetAccessManager.handleFatalError that will stop the - // MessageProcessor thread and restart it that will lead again - // to an OOM error and so on... So stop here right now + // if there is an OOM error here, stop here right now try { sTran.start(); diff --git a/src/main/java/org/ice4j/util/ExecutorFactory.java b/src/main/java/org/ice4j/util/ExecutorFactory.java index b85adbe..0477533 100644 --- a/src/main/java/org/ice4j/util/ExecutorFactory.java +++ b/src/main/java/org/ice4j/util/ExecutorFactory.java @@ -22,6 +22,8 @@ import java.util.concurrent.*; /** * Helper class which contains functions to create pre-configured executors + * + * @author Yura Yaroshevich */ public class ExecutorFactory { @@ -112,4 +114,27 @@ public class ExecutorFactory executor.setRemoveOnCancelPolicy(true); return Executors.unconfigurableScheduledExecutorService(executor); } + + /** + * Creates a {@link ExecutorService} with limited number of threads which + * are released after idle timeout. + * + * @param threadsLimit - numbers of threads in pool + * @param threadNamePrefix - name prefix for threads created by pool + * @return pre-configured {@link ExecutorService} + */ + public static ExecutorService createFixedThreadPool( + int threadsLimit, + String threadNamePrefix) + { + final CustomizableThreadFactory threadFactory + = new CustomizableThreadFactory(threadNamePrefix, true); + + final ThreadPoolExecutor executor = new ThreadPoolExecutor( + threadsLimit, threadsLimit, 60L, TimeUnit.SECONDS, + new LinkedBlockingDeque<>(), threadFactory); + executor.allowCoreThreadTimeOut(true); + + return Executors.unconfigurableExecutorService(executor); + } }