001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.concurrent;
016    
017    import java.util.concurrent.Future;
018    
019    /**
020     * Handles rejected tasks by canceling them immediately.
021     *
022     * <p>
023     * Use this policy for efficiently discarding rejected tasks. Unlike {@link
024     * CallerRunsPolicy}, this policy maintains the order of tasks in the task
025     * queue. Unlike {@link DiscardOldestPolicy} and {@link DiscardPolicy}, which
026     * ultimately call {@link Future#get()}, threads do not block waiting for a
027     * timeout.
028     * </p>
029     *
030     * @author Shuyang Zhou
031     */
032    public class DiscardWithCancelPolicy implements RejectedExecutionHandler {
033    
034            /**
035             * Rejects execution of the {@link Runnable} task by canceling it
036             * immediately.
037             *
038             * <p>
039             * Important: The task can only be canceled if it is a subtype of {@link
040             * Future}.
041             * </p>
042             *
043             * @param runnable the task
044             * @param threadPoolExecutor the executor
045             */
046            @Override
047            public void rejectedExecution(
048                    Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
049    
050                    if (runnable instanceof Future<?>) {
051                            Future<?> future = (Future<?>)runnable;
052    
053                            // There is no point to try and interrupt the runner thread since
054                            // being rejected means it is not yet running
055    
056                            future.cancel(false);
057                    }
058            }
059    
060    }