001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }