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 java.util.concurrent.RejectedExecutionHandler;
12 import java.util.concurrent.ThreadPoolExecutor;
13 import java.util.concurrent.atomic.AtomicLong;
15 import org.opendaylight.yangtools.util.ExecutorServiceUtil;
17 import com.google.common.base.Preconditions;
20 * A RejectedExecutionHandler that delegates to a backing RejectedExecutionHandler and counts the
21 * number of rejected tasks.
23 * @author Thomas Pantelis
25 public class CountingRejectedExecutionHandler implements RejectedExecutionHandler {
27 private final RejectedExecutionHandler delegate;
28 private final AtomicLong rejectedTaskCounter = new AtomicLong();
33 * @param delegate the backing RejectedExecutionHandler.
35 public CountingRejectedExecutionHandler( RejectedExecutionHandler delegate ) {
36 this.delegate = Preconditions.checkNotNull( delegate );
40 public void rejectedExecution( Runnable task, ThreadPoolExecutor executor ) {
41 rejectedTaskCounter.incrementAndGet();
42 delegate.rejectedExecution( task, executor );
46 * Returns the rejected task count.
48 public long getRejectedTaskCount(){
49 return rejectedTaskCounter.get();
53 * Returns s counting handler for rejected tasks that runs the rejected task directly in the
54 * calling thread of the execute method, unless the executor has been shut down, in which case
55 * the task is discarded.
57 public static CountingRejectedExecutionHandler newCallerRunsPolicy() {
58 return new CountingRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() );
62 * Returns a counting handler for rejected tasks that throws a RejectedExecutionException.
64 public static CountingRejectedExecutionHandler newAbortPolicy() {
65 return new CountingRejectedExecutionHandler( new ThreadPoolExecutor.AbortPolicy() );
69 * Returns a counting handler for rejected tasks that that blocks on the
70 * {@link ThreadPoolExecutor}'s backing queue until it can add the task to the queue.
72 public static CountingRejectedExecutionHandler newCallerWaitsPolicy() {
73 return new CountingRejectedExecutionHandler( ExecutorServiceUtil.waitInQueueExecutionHandler() );