Import atomix/{storage,utils}
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / concurrent / ThreadPoolContext.java
1 /*
2  * Copyright 2015-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.utils.concurrent;
17
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import java.time.Duration;
22 import java.util.LinkedList;
23 import java.util.concurrent.Executor;
24 import java.util.concurrent.ScheduledExecutorService;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27
28 import static com.google.common.base.Preconditions.checkNotNull;
29
30 /**
31  * Thread pool context.
32  * <p>
33  * This is a special {@link ThreadContext} implementation that schedules events to be executed
34  * on a thread pool. Events executed by this context are guaranteed to be executed on order but may be executed on different
35  * threads in the provided thread pool.
36  *
37  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
38  */
39 public class ThreadPoolContext extends AbstractThreadContext {
40   private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolContext.class);
41   protected final ScheduledExecutorService parent;
42   private final Runnable runner;
43   private final LinkedList<Runnable> tasks = new LinkedList<>();
44   private boolean running;
45   private final Executor executor = new Executor() {
46     @Override
47     public void execute(Runnable command) {
48       synchronized (tasks) {
49         tasks.add(command);
50         if (!running) {
51           running = true;
52           parent.execute(runner);
53         }
54       }
55     }
56   };
57
58   /**
59    * Creates a new thread pool context.
60    *
61    * @param parent The thread pool on which to execute events.
62    */
63   public ThreadPoolContext(ScheduledExecutorService parent) {
64     this.parent = checkNotNull(parent, "parent cannot be null");
65
66     // This code was shamelessly stolededed from Vert.x:
67     // https://github.com/eclipse/vert.x/blob/master/src/main/java/io/vertx/core/impl/OrderedExecutorFactory.java
68     runner = () -> {
69       ((AtomixThread) Thread.currentThread()).setContext(this);
70       for (;;) {
71         final Runnable task;
72         synchronized (tasks) {
73           task = tasks.poll();
74           if (task == null) {
75             running = false;
76             return;
77           }
78         }
79
80         try {
81           task.run();
82         } catch (Throwable t) {
83           LOGGER.error("An uncaught exception occurred", t);
84           throw t;
85         }
86       }
87     };
88   }
89
90   @Override
91   public void execute(Runnable command) {
92     executor.execute(command);
93   }
94
95   @Override
96   public Scheduled schedule(Duration delay, Runnable runnable) {
97     ScheduledFuture<?> future = parent.schedule(() -> executor.execute(runnable), delay.toMillis(), TimeUnit.MILLISECONDS);
98     return () -> future.cancel(false);
99   }
100
101   @Override
102   public Scheduled schedule(Duration delay, Duration interval, Runnable runnable) {
103     ScheduledFuture<?> future = parent.scheduleAtFixedRate(() -> executor.execute(runnable), delay.toMillis(), interval.toMillis(), TimeUnit.MILLISECONDS);
104     return () -> future.cancel(false);
105   }
106
107   @Override
108   public void close() {
109     // Do nothing.
110   }
111
112 }