2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.util;
10 import java.util.concurrent.BlockingQueue;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.RejectedExecutionException;
13 import java.util.concurrent.RejectedExecutionHandler;
14 import java.util.concurrent.ThreadPoolExecutor;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 import com.google.common.util.concurrent.ForwardingBlockingQueue;
22 * Utility methods for dealing with {@link ExecutorService}s.
24 public final class ExecutorServiceUtil {
25 private static final class WaitInQueueExecutionHandler implements RejectedExecutionHandler {
27 public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
29 executor.getQueue().put(r);
30 } catch (InterruptedException e) {
31 LOG.debug("Intterupted while waiting for queue", e);
32 throw new RejectedExecutionException("Interrupted while waiting for queue", e);
37 private static final Logger LOG = LoggerFactory.getLogger(ExecutorServiceUtil.class);
38 private static final RejectedExecutionHandler WAIT_IN_QUEUE_HANDLER = new WaitInQueueExecutionHandler();
40 private ExecutorServiceUtil() {
41 throw new UnsupportedOperationException("Utility class");
45 * Create a {@link BlockingQueue} which does not allow for non-blocking addition to the queue.
46 * This is useful with {@link #waitInQueueExecutionHandler()} to turn force a
47 * {@link ThreadPoolExecutor} to create as many threads as it is configured to before starting
50 * @param delegate Backing blocking queue.
51 * @return A new blocking queue backed by the delegate
53 public <E> BlockingQueue<E> offerFailingBlockingQueue(final BlockingQueue<E> delegate) {
54 return new ForwardingBlockingQueue<E>() {
56 public boolean offer(final E o) {
61 protected BlockingQueue<E> delegate() {
68 * Return a {@link RejectedExecutionHandler} which blocks on the {@link ThreadPoolExecutor}'s
69 * backing queue if a new thread cannot be spawned.
71 * @return A shared RejectedExecutionHandler instance.
73 public RejectedExecutionHandler waitInQueueExecutionHandler() {
74 return WAIT_IN_QUEUE_HANDLER;