/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.util;

import EDU.oswego.cs.dl.util.concurrent.Executor;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.activemq.service.Service;

import javax.jms.JMSException;

/**
 * A helper class for working with  {@link Executor} objects
 *
 * @version $Revision: 1.1.1.1 $
 */
public class ExecutorHelper {
    private static final Log log = LogFactory.getLog(ExecutorHelper.class);

    /**
     * A helper method to stop the execution of an executor
     *
     * @param executor the executor or null if one is not created yet
     */
    public static void stopExecutor(Executor executor) throws InterruptedException, JMSException {
        if (executor instanceof Service) {
            Service service = (Service) executor;
            service.stop();
        }
        else if (executor instanceof PooledExecutor) {
            PooledExecutor pe = (PooledExecutor) executor;
            pe.shutdownAfterProcessingCurrentlyQueuedTasks();
            //pe.shutdownNow();
            pe.awaitTerminationAfterShutdown();
        }
        else if (executor != null) {
            log.warn("Don't know how to cleanly close down the given executor: " + executor
                    + ". Consider deriving from this class to implement the Service interface to shut down cleanly");
        }
    }

}
