001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.servicemix.executors.impl;
018
019 import java.util.concurrent.BlockingQueue;
020 import java.util.concurrent.ThreadPoolExecutor;
021 import java.util.concurrent.TimeUnit;
022
023 import org.apache.servicemix.executors.Executor;
024
025 /**
026 * The default Executor implementation which uses a
027 * ThreadPoolExecutor underneath.
028 *
029 * @author <a href="mailto:gnodet [at] gmail.com">Guillaume Nodet</a>
030 */
031 public class ExecutorImpl implements Executor {
032
033 private final ThreadPoolExecutor threadPool;
034
035 private final long shutdownDelay;
036
037 public ExecutorImpl(ThreadPoolExecutor threadPool, long shutdownDelay) {
038 this.threadPool = threadPool;
039 this.shutdownDelay = shutdownDelay;
040 }
041
042 public void execute(Runnable command) {
043 threadPool.execute(command);
044 }
045
046 public void shutdown() {
047 threadPool.shutdown();
048 if (!threadPool.isTerminated() && shutdownDelay > 0) {
049 new Thread(new Runnable() {
050 public void run() {
051 try {
052 if (!threadPool.awaitTermination(shutdownDelay, TimeUnit.MILLISECONDS)) {
053 threadPool.shutdownNow();
054 }
055 } catch (InterruptedException e) {
056 // Do nothing
057 }
058 }
059 }).start();
060 }
061 }
062
063 public int capacity() {
064 BlockingQueue queue = threadPool.getQueue();
065 return queue.remainingCapacity() + queue.size();
066 }
067
068 public int size() {
069 BlockingQueue queue = threadPool.getQueue();
070 return queue.size();
071 }
072
073 }