2 * Copyright (c) 2014 Brocade Communications 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
9 package org.opendaylight.yangtools.util.concurrent;
11 import com.google.common.base.Preconditions;
12 import java.util.concurrent.RejectedExecutionHandler;
13 import java.util.concurrent.ThreadPoolExecutor;
14 import java.util.concurrent.atomic.LongAdder;
15 import org.opendaylight.yangtools.util.ExecutorServiceUtil;
18 * A RejectedExecutionHandler that delegates to a backing RejectedExecutionHandler and counts the
19 * number of rejected tasks.
21 * @author Thomas Pantelis
23 public class CountingRejectedExecutionHandler implements RejectedExecutionHandler {
24 private final LongAdder rejectedTaskCounter = new LongAdder();
25 private final RejectedExecutionHandler delegate;
30 * @param delegate the backing RejectedExecutionHandler.
32 public CountingRejectedExecutionHandler( final RejectedExecutionHandler delegate ) {
33 this.delegate = Preconditions.checkNotNull( delegate );
37 public void rejectedExecution( final Runnable task, final ThreadPoolExecutor executor ) {
38 rejectedTaskCounter.increment();
39 delegate.rejectedExecution(task, executor);
43 * Returns the rejected task count.
45 public long getRejectedTaskCount() {
46 return rejectedTaskCounter.sum();
50 * Returns s counting handler for rejected tasks that runs the rejected task directly in the
51 * calling thread of the execute method, unless the executor has been shut down, in which case
52 * the task is discarded.
54 public static CountingRejectedExecutionHandler newCallerRunsPolicy() {
55 return new CountingRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
59 * Returns a counting handler for rejected tasks that throws a RejectedExecutionException.
61 public static CountingRejectedExecutionHandler newAbortPolicy() {
62 return new CountingRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
66 * Returns a counting handler for rejected tasks that that blocks on the
67 * {@link ThreadPoolExecutor}'s backing queue until it can add the task to the queue.
69 public static CountingRejectedExecutionHandler newCallerWaitsPolicy() {
70 return new CountingRejectedExecutionHandler(ExecutorServiceUtil.waitInQueueExecutionHandler());