View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
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  
17  package com.google.common.util.concurrent;
18  
19  import com.google.common.annotations.VisibleForTesting;
20  import com.google.common.base.Preconditions;
21  
22  import java.util.concurrent.Executor;
23  import java.util.logging.Level;
24  import java.util.logging.Logger;
25  
26  import javax.annotation.Nullable;
27  import javax.annotation.concurrent.GuardedBy;
28  
29  /**
30   * <p>A list of listeners, each with an associated {@code Executor}, that
31   * guarantees that every {@code Runnable} that is {@linkplain #add added} will
32   * be executed after {@link #execute()} is called. Any {@code Runnable} added
33   * after the call to {@code execute} is still guaranteed to execute. There is no
34   * guarantee, however, that listeners will be executed in the order that they
35   * are added.
36   *
37   * <p>Exceptions thrown by a listener will be propagated up to the executor.
38   * Any exception thrown during {@code Executor.execute} (e.g., a {@code
39   * RejectedExecutionException} or an exception thrown by {@linkplain
40   * MoreExecutors#directExecutor direct execution}) will be caught and
41   * logged.
42   *
43   * @author Nishant Thakkar
44   * @author Sven Mawson
45   * @since 1.0
46   */
47  public final class ExecutionList {
48    // Logger to log exceptions caught when running runnables.
49    @VisibleForTesting static final Logger log = Logger.getLogger(ExecutionList.class.getName());
50  
51    /**
52     * The runnable, executor pairs to execute.  This acts as a stack threaded through the 
53     * {@link RunnableExecutorPair#next} field.
54     */
55    @GuardedBy("this")
56    private RunnableExecutorPair runnables;
57    @GuardedBy("this")
58    private boolean executed;
59  
60    /** Creates a new, empty {@link ExecutionList}. */
61    public ExecutionList() {}
62  
63    /**
64     * Adds the {@code Runnable} and accompanying {@code Executor} to the list of
65     * listeners to execute. If execution has already begun, the listener is
66     * executed immediately.
67     *
68     * <p>Note: For fast, lightweight listeners that would be safe to execute in
69     * any thread, consider {@link MoreExecutors#directExecutor}. For heavier
70     * listeners, {@code directExecutor()} carries some caveats: First, the
71     * thread that the listener runs in depends on whether the {@code
72     * ExecutionList} has been executed at the time it is added. In particular,
73     * listeners may run in the thread that calls {@code add}. Second, the thread
74     * that calls {@link #execute} may be an internal implementation thread, such
75     * as an RPC network thread, and {@code directExecutor()} listeners may
76     * run in this thread. Finally, during the execution of a {@code
77     * directExecutor} listener, all other registered but unexecuted
78     * listeners are prevented from running, even if those listeners are to run
79     * in other executors.
80     */
81    public void add(Runnable runnable, Executor executor) {
82      // Fail fast on a null.  We throw NPE here because the contract of
83      // Executor states that it throws NPE on null listener, so we propagate
84      // that contract up into the add method as well.
85      Preconditions.checkNotNull(runnable, "Runnable was null.");
86      Preconditions.checkNotNull(executor, "Executor was null.");
87  
88      // Lock while we check state.  We must maintain the lock while adding the
89      // new pair so that another thread can't run the list out from under us.
90      // We only add to the list if we have not yet started execution.
91      synchronized (this) {
92        if (!executed) {
93          runnables = new RunnableExecutorPair(runnable, executor, runnables);
94          return;
95        }
96      }
97      // Execute the runnable immediately. Because of scheduling this may end up
98      // getting called before some of the previously added runnables, but we're
99      // OK with that.  If we want to change the contract to guarantee ordering
100     // among runnables we'd have to modify the logic here to allow it.
101     executeListener(runnable, executor);
102   }
103 
104   /**
105    * Runs this execution list, executing all existing pairs in the order they
106    * were added. However, note that listeners added after this point may be
107    * executed before those previously added, and note that the execution order
108    * of all listeners is ultimately chosen by the implementations of the
109    * supplied executors.
110    *
111    * <p>This method is idempotent. Calling it several times in parallel is
112    * semantically equivalent to calling it exactly once.
113    *
114    * @since 10.0 (present in 1.0 as {@code run})
115    */
116   public void execute() {
117     // Lock while we update our state so the add method above will finish adding
118     // any listeners before we start to run them.
119     RunnableExecutorPair list;
120     synchronized (this) {
121       if (executed) {
122         return;
123       }
124       executed = true;
125       list = runnables;
126       runnables = null;  // allow GC to free listeners even if this stays around for a while.
127     }
128     // If we succeeded then list holds all the runnables we to execute.  The pairs in the stack are
129     // in the opposite order from how they were added so we need to reverse the list to fulfill our
130     // contract.
131     // This is somewhat annoying, but turns out to be very fast in practice.  Alternatively, we 
132     // could drop the contract on the method that enforces this queue like behavior since depending
133     // on it is likely to be a bug anyway.
134     
135     // N.B. All writes to the list and the next pointers must have happened before the above 
136     // synchronized block, so we can iterate the list without the lock held here.
137     RunnableExecutorPair reversedList = null;
138     while (list != null) {
139       RunnableExecutorPair tmp = list;
140       list = list.next;
141       tmp.next = reversedList;
142       reversedList = tmp;
143     }
144     while (reversedList != null) {
145       executeListener(reversedList.runnable, reversedList.executor);
146       reversedList = reversedList.next;
147     }
148   }
149 
150   /**
151    * Submits the given runnable to the given {@link Executor} catching and logging all 
152    * {@linkplain RuntimeException runtime exceptions} thrown by the executor.
153    */
154   private static void executeListener(Runnable runnable, Executor executor) {
155     try {
156       executor.execute(runnable);
157     } catch (RuntimeException e) {
158       // Log it and keep going, bad runnable and/or executor.  Don't
159       // punish the other runnables if we're given a bad one.  We only
160       // catch RuntimeException because we want Errors to propagate up.
161       log.log(Level.SEVERE, "RuntimeException while executing runnable "
162           + runnable + " with executor " + executor, e);
163     }
164   }
165 
166   private static final class RunnableExecutorPair {
167     final Runnable runnable;
168     final Executor executor;
169     @Nullable RunnableExecutorPair next;
170 
171     RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
172       this.runnable = runnable;
173       this.executor = executor;
174       this.next = next;
175     }
176   }
177 }