View Javadoc
1   /*
2    * Copyright 2013 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.concurrent;
17  
18  import io.netty.util.internal.UnstableApi;
19  import io.netty.util.internal.logging.InternalLogger;
20  import io.netty.util.internal.logging.InternalLoggerFactory;
21  
22  import org.jetbrains.annotations.Async.Execute;
23  import org.jetbrains.annotations.Async.Schedule;
24  
25  import java.util.Collection;
26  import java.util.Collections;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.concurrent.AbstractExecutorService;
30  import java.util.concurrent.Callable;
31  import java.util.concurrent.RunnableFuture;
32  import java.util.concurrent.TimeUnit;
33  
34  /**
35   * Abstract base class for {@link EventExecutor} implementations.
36   */
37  public abstract class AbstractEventExecutor extends AbstractExecutorService implements EventExecutor {
38      private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractEventExecutor.class);
39  
40      static final long DEFAULT_SHUTDOWN_QUIET_PERIOD = 2;
41      static final long DEFAULT_SHUTDOWN_TIMEOUT = 15;
42  
43      private final EventExecutorGroup parent;
44      private final Collection<EventExecutor> selfCollection = Collections.<EventExecutor>singleton(this);
45  
46      protected AbstractEventExecutor() {
47          this(null);
48      }
49  
50      protected AbstractEventExecutor(EventExecutorGroup parent) {
51          this.parent = parent;
52      }
53  
54      @Override
55      public EventExecutorGroup parent() {
56          return parent;
57      }
58  
59      @Override
60      public EventExecutor next() {
61          return this;
62      }
63  
64      @Override
65      public boolean inEventLoop() {
66          return inEventLoop(Thread.currentThread());
67      }
68  
69      @Override
70      public Iterator<EventExecutor> iterator() {
71          return selfCollection.iterator();
72      }
73  
74      @Override
75      public Future<?> shutdownGracefully() {
76          return shutdownGracefully(DEFAULT_SHUTDOWN_QUIET_PERIOD, DEFAULT_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS);
77      }
78  
79      /**
80       * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead.
81       */
82      @Override
83      @Deprecated
84      public abstract void shutdown();
85  
86      /**
87       * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead.
88       */
89      @Override
90      @Deprecated
91      public List<Runnable> shutdownNow() {
92          shutdown();
93          return Collections.emptyList();
94      }
95  
96      @Override
97      public <V> Promise<V> newPromise() {
98          return new DefaultPromise<V>(this);
99      }
100 
101     @Override
102     public <V> ProgressivePromise<V> newProgressivePromise() {
103         return new DefaultProgressivePromise<V>(this);
104     }
105 
106     @Override
107     public <V> Future<V> newSucceededFuture(V result) {
108         return new SucceededFuture<V>(this, result);
109     }
110 
111     @Override
112     public <V> Future<V> newFailedFuture(Throwable cause) {
113         return new FailedFuture<V>(this, cause);
114     }
115 
116     @Override
117     public Future<?> submit(Runnable task) {
118         return (Future<?>) super.submit(task);
119     }
120 
121     @Override
122     public <T> Future<T> submit(Runnable task, T result) {
123         return (Future<T>) super.submit(task, result);
124     }
125 
126     @Override
127     public <T> Future<T> submit(Callable<T> task) {
128         return (Future<T>) super.submit(task);
129     }
130 
131     @Override
132     protected final <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
133         return new PromiseTask<T>(this, runnable, value);
134     }
135 
136     @Override
137     protected final <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
138         return new PromiseTask<T>(this, callable);
139     }
140 
141     @Override
142     public ScheduledFuture<?> schedule(Runnable command, long delay,
143                                        TimeUnit unit) {
144         throw new UnsupportedOperationException();
145     }
146 
147     @Override
148     public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
149         throw new UnsupportedOperationException();
150     }
151 
152     @Override
153     public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
154         throw new UnsupportedOperationException();
155     }
156 
157     @Override
158     public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
159         throw new UnsupportedOperationException();
160     }
161 
162     /**
163      * Try to execute the given {@link Runnable} and just log if it throws a {@link Throwable}.
164      */
165     protected static void safeExecute(Runnable task) {
166         try {
167             runTask(task);
168         } catch (Throwable t) {
169             logger.warn("A task raised an exception. Task: {}", task, t);
170         }
171     }
172 
173     protected static void runTask(@Execute Runnable task) {
174         task.run();
175     }
176 
177     /**
178      * Like {@link #execute(Runnable)} but does not guarantee the task will be run until either
179      * a non-lazy task is executed or the executor is shut down.
180      *
181      * This is equivalent to submitting a {@link AbstractEventExecutor.LazyRunnable} to
182      * {@link #execute(Runnable)} but for an arbitrary {@link Runnable}.
183      *
184      * The default implementation just delegates to {@link #execute(Runnable)}.
185      */
186     @UnstableApi
187     public void lazyExecute(Runnable task) {
188         lazyExecute0(task);
189     }
190 
191     private void lazyExecute0(@Schedule Runnable task) {
192         execute(task);
193     }
194 
195     /**
196      * Marker interface for {@link Runnable} to indicate that it should be queued for execution
197      * but does not need to run immediately.
198      */
199     @UnstableApi
200     public interface LazyRunnable extends Runnable { }
201 }