001/*
002 * Copyright 2010-2015 Institut Pasteur.
003 * 
004 * This file is part of Icy.
005 * 
006 * Icy is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 * 
011 * Icy is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 * GNU General Public License for more details.
015 * 
016 * You should have received a copy of the GNU General Public License
017 * along with Icy. If not, see <http://www.gnu.org/licenses/>.
018 */
019package icy.system.thread;
020
021import java.util.concurrent.FutureTask;
022
023/**
024 * @author stephane
025 */
026public class SingleProcessor extends Processor
027{
028    private final boolean queueEnabled;
029
030    /**
031     * 
032     */
033    public SingleProcessor(boolean enableQueue, String name)
034    {
035        super(1, 1);
036
037        queueEnabled = enableQueue;
038        setRejectedExecutionHandler(new DiscardPolicy());
039        setThreadName(name);
040    }
041
042    /**
043     * 
044     */
045    public SingleProcessor(boolean enableQueue)
046    {
047        this(enableQueue, "SingleProcessor");
048    }
049
050    /**
051     * Try to submit the specified task for execution and returns a Future representing that task.<br>
052     * The Future's <tt>get</tt> method will return <tt>null</tt> upon <em>successful</em>
053     * completion.<br>
054     * Returns a <code>null</code> Future object if processor is already processing or queue is not
055     * empty (depending the {@link #isQueueEnabled()} parameter) to notify the task has been
056     * ignored.
057     */
058    @Override
059    protected synchronized <T> FutureTask<T> submit(FutureTaskAdapter<T> task)
060    {
061        // add task only if not already processing or queue empty
062        if (getActiveCount() == 0)
063            return super.submit(task);
064
065        if (queueEnabled)
066        {
067            removeAllWaitingTasks();
068            return super.submit(task);
069        }
070
071        // return null mean the task was ignored
072        return null;
073    }
074
075    /**
076     * @deprecated use {@link #submit(Runnable)} instead.
077     */
078    @Deprecated
079    public synchronized boolean requestProcess(Runnable task)
080    {
081        return submit(task) != null;
082    }
083
084    /**
085     * @deprecated use {@link #submit(Runnable, boolean)} instead
086     */
087    @Deprecated
088    public synchronized boolean requestProcess(Runnable task, boolean onAWTEventThread)
089    {
090        return submit(task, onAWTEventThread) != null;
091    }
092
093    public boolean isQueueEnabled()
094    {
095        return queueEnabled;
096    }
097}