1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.tomcat.util.threads;
18
19 import java.util.List;
20 import java.util.concurrent.AbstractExecutorService;
21 import java.util.concurrent.RejectedExecutionException;
22 import java.util.concurrent.TimeUnit;
23
24 public class InlineExecutorService extends AbstractExecutorService {
25
26     private volatile boolean shutdown;
27     private volatile boolean taskRunning;
28     private volatile boolean terminated;
29
30     private final Object lock = new Object();
31
32     @Override
33     public void shutdown() {
34         shutdown = true;
35         synchronized (lock) {
36             terminated = !taskRunning;
37         }
38     }
39
40     @Override
41     public List<Runnable> shutdownNow() {
42         shutdown();
43         return null;
44     }
45
46     @Override
47     public boolean isShutdown() {
48         return shutdown;
49     }
50
51     @Override
52     public boolean isTerminated() {
53         return terminated;
54     }
55
56     @Override
57     public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
58         synchronized (lock) {
59             if (terminated) {
60                 return true;
61             }
62             lock.wait(unit.toMillis(timeout));
63             return terminated;
64         }
65     }
66
67     @Override
68     public void execute(Runnable command) {
69         synchronized (lock) {
70             if (shutdown) {
71                 throw new RejectedExecutionException();
72             }
73             taskRunning = true;
74         }
75         command.run();
76         synchronized (lock) {
77             taskRunning = false;
78             if (shutdown) {
79                 terminated = true;
80                 lock.notifyAll();
81             }
82         }
83     }
84 }
85