• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.base.Preconditions;
20 import com.google.common.collect.Lists;
21 
22 import java.util.Queue;
23 import java.util.concurrent.Executor;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 
27 /**
28  * <p>A list of listeners, each with an associated {@code Executor}, that
29  * guarantees that every {@code Runnable} that is {@linkplain #add added} will
30  * be executed after {@link #execute()} is called. Any {@code Runnable} added
31  * after the call to {@code execute} is still guaranteed to execute. There is no
32  * guarantee, however, that listeners will be executed in the order that they
33  * are added.
34  *
35  * <p>Exceptions thrown by a listener will be propagated up to the executor.
36  * Any exception thrown during {@code Executor.execute} (e.g., a {@code
37  * RejectedExecutionException} or an exception thrown by {@linkplain
38  * MoreExecutors#sameThreadExecutor inline execution}) will be caught and
39  * logged.
40  *
41  * @author Nishant Thakkar
42  * @author Sven Mawson
43  * @since 1.0
44  */
45 public final class ExecutionList {
46 
47   // Logger to log exceptions caught when running runnables.
48   private static final Logger log =
49       Logger.getLogger(ExecutionList.class.getName());
50 
51   // The runnable,executor pairs to execute.
52   private final Queue<RunnableExecutorPair> runnables = Lists.newLinkedList();
53 
54   // Boolean we use mark when execution has started.  Only accessed from within
55   // synchronized blocks.
56   private boolean executed = false;
57 
58   /** Creates a new, empty {@link ExecutionList}. */
ExecutionList()59   public ExecutionList() {
60   }
61 
62   /**
63    * Adds the {@code Runnable} and accompanying {@code Executor} to the list of
64    * listeners to execute. If execution has already begun, the listener is
65    * executed immediately.
66    *
67    * <p>Note: For fast, lightweight listeners that would be safe to execute in
68    * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
69    * listeners, {@code sameThreadExecutor()} carries some caveats: First, the
70    * thread that the listener runs in depends on whether the {@code
71    * ExecutionList} has been executed at the time it is added. In particular,
72    * listeners may run in the thread that calls {@code add}. Second, the thread
73    * that calls {@link #execute} may be an internal implementation thread, such
74    * as an RPC network thread, and {@code sameThreadExecutor()} listeners may
75    * run in this thread. Finally, during the execution of a {@code
76    * sameThreadExecutor} listener, all other registered but unexecuted
77    * listeners are prevented from running, even if those listeners are to run
78    * in other executors.
79    */
add(Runnable runnable, Executor executor)80   public void add(Runnable runnable, Executor executor) {
81     // Fail fast on a null.  We throw NPE here because the contract of
82     // Executor states that it throws NPE on null listener, so we propagate
83     // that contract up into the add method as well.
84     Preconditions.checkNotNull(runnable, "Runnable was null.");
85     Preconditions.checkNotNull(executor, "Executor was null.");
86 
87     boolean executeImmediate = false;
88 
89     // Lock while we check state.  We must maintain the lock while adding the
90     // new pair so that another thread can't run the list out from under us.
91     // We only add to the list if we have not yet started execution.
92     synchronized (runnables) {
93       if (!executed) {
94         runnables.add(new RunnableExecutorPair(runnable, executor));
95       } else {
96         executeImmediate = true;
97       }
98     }
99 
100     // Execute the runnable immediately. Because of scheduling this may end up
101     // getting called before some of the previously added runnables, but we're
102     // OK with that.  If we want to change the contract to guarantee ordering
103     // among runnables we'd have to modify the logic here to allow it.
104     if (executeImmediate) {
105       new RunnableExecutorPair(runnable, executor).execute();
106     }
107   }
108 
109   /**
110    * Runs this execution list, executing all existing pairs in the order they
111    * were added. However, note that listeners added after this point may be
112    * executed before those previously added, and note that the execution order
113    * of all listeners is ultimately chosen by the implementations of the
114    * supplied executors.
115    *
116    * <p>This method is idempotent. Calling it several times in parallel is
117    * semantically equivalent to calling it exactly once.
118    *
119    * @since 10.0 (present in 1.0 as {@code run})
120    */
execute()121   public void execute() {
122     // Lock while we update our state so the add method above will finish adding
123     // any listeners before we start to run them.
124     synchronized (runnables) {
125       if (executed) {
126         return;
127       }
128       executed = true;
129     }
130 
131     // At this point the runnables will never be modified by another
132     // thread, so we are safe using it outside of the synchronized block.
133     while (!runnables.isEmpty()) {
134       runnables.poll().execute();
135     }
136   }
137 
138   private static class RunnableExecutorPair {
139     final Runnable runnable;
140     final Executor executor;
141 
RunnableExecutorPair(Runnable runnable, Executor executor)142     RunnableExecutorPair(Runnable runnable, Executor executor) {
143       this.runnable = runnable;
144       this.executor = executor;
145     }
146 
execute()147     void execute() {
148       try {
149         executor.execute(runnable);
150       } catch (RuntimeException e) {
151         // Log it and keep going, bad runnable and/or executor.  Don't
152         // punish the other runnables if we're given a bad one.  We only
153         // catch RuntimeException because we want Errors to propagate up.
154         log.log(Level.SEVERE, "RuntimeException while executing runnable "
155             + runnable + " with executor " + executor, e);
156       }
157     }
158   }
159 }
160