001 /*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.util.concurrent;
018
019 import com.google.common.base.Preconditions;
020 import com.google.common.collect.Lists;
021
022 import java.util.Queue;
023 import java.util.concurrent.Executor;
024 import java.util.logging.Level;
025 import java.util.logging.Logger;
026
027 /**
028 * <p>A list of listeners, each with an associated {@code Executor}, that
029 * guarantees that every {@code Runnable} that is {@linkplain #add added} will
030 * be executed after {@link #execute()} is called. Any {@code Runnable} added
031 * after the call to {@code execute} is still guaranteed to execute. There is no
032 * guarantee, however, that listeners will be executed in the order that they
033 * are added.
034 *
035 * <p>Exceptions thrown by a listener will be propagated up to the executor.
036 * Any exception thrown during {@code Executor.execute} (e.g., a {@code
037 * RejectedExecutionException} or an exception thrown by {@linkplain
038 * MoreExecutors#sameThreadExecutor inline execution}) will be caught and
039 * logged.
040 *
041 * @author Nishant Thakkar
042 * @author Sven Mawson
043 * @since 1.0
044 */
045 public final class ExecutionList {
046
047 // Logger to log exceptions caught when running runnables.
048 private static final Logger log =
049 Logger.getLogger(ExecutionList.class.getName());
050
051 // The runnable,executor pairs to execute.
052 private final Queue<RunnableExecutorPair> runnables = Lists.newLinkedList();
053
054 // Boolean we use mark when execution has started. Only accessed from within
055 // synchronized blocks.
056 private boolean executed = false;
057
058 /** Creates a new, empty {@link ExecutionList}. */
059 public ExecutionList() {
060 }
061
062 /**
063 * Adds the {@code Runnable} and accompanying {@code Executor} to the list of
064 * listeners to execute. If execution has already begun, the listener is
065 * executed immediately.
066 *
067 * <p>Note: For fast, lightweight listeners that would be safe to execute in
068 * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
069 * listeners, {@code sameThreadExecutor()} carries some caveats: First, the
070 * thread that the listener runs in depends on whether the {@code
071 * ExecutionList} has been executed at the time it is added. In particular,
072 * listeners may run in the thread that calls {@code add}. Second, the thread
073 * that calls {@link #execute} may be an internal implementation thread, such
074 * as an RPC network thread, and {@code sameThreadExecutor()} listeners may
075 * run in this thread. Finally, during the execution of a {@code
076 * sameThreadExecutor} listener, all other registered but unexecuted
077 * listeners are prevented from running, even if those listeners are to run
078 * in other executors.
079 */
080 public void add(Runnable runnable, Executor executor) {
081 // Fail fast on a null. We throw NPE here because the contract of
082 // Executor states that it throws NPE on null listener, so we propagate
083 // that contract up into the add method as well.
084 Preconditions.checkNotNull(runnable, "Runnable was null.");
085 Preconditions.checkNotNull(executor, "Executor was null.");
086
087 boolean executeImmediate = false;
088
089 // Lock while we check state. We must maintain the lock while adding the
090 // new pair so that another thread can't run the list out from under us.
091 // We only add to the list if we have not yet started execution.
092 synchronized (runnables) {
093 if (!executed) {
094 runnables.add(new RunnableExecutorPair(runnable, executor));
095 } else {
096 executeImmediate = true;
097 }
098 }
099
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 */
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
142 RunnableExecutorPair(Runnable runnable, Executor executor) {
143 this.runnable = runnable;
144 this.executor = executor;
145 }
146
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 }