View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.util.concurrent;
16  
17  import static com.google.common.base.Preconditions.checkNotNull;
18  
19  import com.google.common.annotations.GwtIncompatible;
20  import java.util.concurrent.Executor;
21  import java.util.logging.Level;
22  import java.util.logging.Logger;
23  import javax.annotation.Nullable;
24  import javax.annotation.concurrent.GuardedBy;
25  
26  /**
27   * A support class for {@code ListenableFuture} implementations to manage their listeners. An
28   * instance contains a list of listeners, each with an associated {@code Executor}, and guarantees
29   * that every {@code Runnable} that is {@linkplain #add added} will be executed after {@link
30   * #execute()} is called. Any {@code Runnable} added after the call to {@code execute} is still
31   * guaranteed to execute. There is no guarantee, however, that listeners will be executed in the
32   * order that they are added.
33   *
34   * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
35   * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
36   * thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and logged.
37   *
38   * @author Nishant Thakkar
39   * @author Sven Mawson
40   * @since 1.0
41   */
42  @GwtIncompatible
43  public final class ExecutionList {
44    /** Logger to log exceptions caught when running runnables. */
45    private static final Logger log = Logger.getLogger(ExecutionList.class.getName());
46  
47    /**
48     * The runnable, executor pairs to execute.  This acts as a stack threaded through the {@link
49     * RunnableExecutorPair#next} field.
50     */
51    @GuardedBy("this")
52    private RunnableExecutorPair runnables;
53  
54    @GuardedBy("this")
55    private boolean executed;
56  
57    /** Creates a new, empty {@link ExecutionList}. */
58    public ExecutionList() {}
59  
60    /**
61     * Adds the {@code Runnable} and accompanying {@code Executor} to the list of listeners to
62     * execute. If execution has already begun, the listener is executed immediately.
63     *
64     * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
65     * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
66     * documentation.
67     */
68    public void add(Runnable runnable, Executor executor) {
69      // Fail fast on a null. We throw NPE here because the contract of Executor states that it throws
70      // NPE on null listener, so we propagate that contract up into the add method as well.
71      checkNotNull(runnable, "Runnable was null.");
72      checkNotNull(executor, "Executor was null.");
73  
74      // Lock while we check state. We must maintain the lock while adding the new pair so that
75      // another thread can't run the list out from under us. We only add to the list if we have not
76      // yet started execution.
77      synchronized (this) {
78        if (!executed) {
79          runnables = new RunnableExecutorPair(runnable, executor, runnables);
80          return;
81        }
82      }
83      // Execute the runnable immediately. Because of scheduling this may end up getting called before
84      // some of the previously added runnables, but we're OK with that. If we want to change the
85      // contract to guarantee ordering among runnables we'd have to modify the logic here to allow
86      // it.
87      executeListener(runnable, executor);
88    }
89  
90    /**
91     * Runs this execution list, executing all existing pairs in the order they were added. However,
92     * note that listeners added after this point may be executed before those previously added, and
93     * note that the execution order of all listeners is ultimately chosen by the implementations of
94     * the supplied executors.
95     *
96     * <p>This method is idempotent. Calling it several times in parallel is semantically equivalent
97     * to calling it exactly once.
98     *
99     * @since 10.0 (present in 1.0 as {@code run})
100    */
101   public void execute() {
102     // Lock while we update our state so the add method above will finish adding any listeners
103     // before we start to run them.
104     RunnableExecutorPair list;
105     synchronized (this) {
106       if (executed) {
107         return;
108       }
109       executed = true;
110       list = runnables;
111       runnables = null; // allow GC to free listeners even if this stays around for a while.
112     }
113     // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are
114     // in the opposite order from how they were added so we need to reverse the list to fulfill our
115     // contract.
116     // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could
117     // drop the contract on the method that enforces this queue like behavior since depending on it
118     // is likely to be a bug anyway.
119 
120     // N.B. All writes to the list and the next pointers must have happened before the above
121     // synchronized block, so we can iterate the list without the lock held here.
122     RunnableExecutorPair reversedList = null;
123     while (list != null) {
124       RunnableExecutorPair tmp = list;
125       list = list.next;
126       tmp.next = reversedList;
127       reversedList = tmp;
128     }
129     while (reversedList != null) {
130       executeListener(reversedList.runnable, reversedList.executor);
131       reversedList = reversedList.next;
132     }
133   }
134 
135   /**
136    * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain
137    * RuntimeException runtime exceptions} thrown by the executor.
138    */
139   private static void executeListener(Runnable runnable, Executor executor) {
140     try {
141       executor.execute(runnable);
142     } catch (RuntimeException e) {
143       // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if
144       // we're given a bad one. We only catch RuntimeException because we want Errors to propagate
145       // up.
146       log.log(
147           Level.SEVERE,
148           "RuntimeException while executing runnable " + runnable + " with executor " + executor,
149           e);
150     }
151   }
152 
153   private static final class RunnableExecutorPair {
154     final Runnable runnable;
155     final Executor executor;
156     @Nullable RunnableExecutorPair next;
157 
158     RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
159       this.runnable = runnable;
160       this.executor = executor;
161       this.next = next;
162     }
163   }
164 }