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 017package com.google.common.util.concurrent; 018 019import com.google.common.annotations.VisibleForTesting; 020import com.google.common.base.Preconditions; 021 022import java.util.concurrent.Executor; 023import java.util.logging.Level; 024import java.util.logging.Logger; 025 026import javax.annotation.Nullable; 027import javax.annotation.concurrent.GuardedBy; 028 029/** 030 * <p>A list of listeners, each with an associated {@code Executor}, that 031 * guarantees that every {@code Runnable} that is {@linkplain #add added} will 032 * be executed after {@link #execute()} is called. Any {@code Runnable} added 033 * after the call to {@code execute} is still guaranteed to execute. There is no 034 * guarantee, however, that listeners will be executed in the order that they 035 * are added. 036 * 037 * <p>Exceptions thrown by a listener will be propagated up to the executor. 038 * Any exception thrown during {@code Executor.execute} (e.g., a {@code 039 * RejectedExecutionException} or an exception thrown by {@linkplain 040 * MoreExecutors#sameThreadExecutor inline execution}) will be caught and 041 * logged. 042 * 043 * @author Nishant Thakkar 044 * @author Sven Mawson 045 * @since 1.0 046 */ 047public final class ExecutionList { 048 // Logger to log exceptions caught when running runnables. 049 @VisibleForTesting static final Logger log = Logger.getLogger(ExecutionList.class.getName()); 050 051 /** 052 * The runnable, executor pairs to execute. This acts as a stack threaded through the 053 * {@link RunnableExecutorPair#next} field. 054 */ 055 @GuardedBy("this") 056 private RunnableExecutorPair runnables; 057 @GuardedBy("this") 058 private boolean executed; 059 060 /** Creates a new, empty {@link ExecutionList}. */ 061 public ExecutionList() {} 062 063 /** 064 * Adds the {@code Runnable} and accompanying {@code Executor} to the list of 065 * listeners to execute. If execution has already begun, the listener is 066 * executed immediately. 067 * 068 * <p>Note: For fast, lightweight listeners that would be safe to execute in 069 * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier 070 * listeners, {@code sameThreadExecutor()} carries some caveats: First, the 071 * thread that the listener runs in depends on whether the {@code 072 * ExecutionList} has been executed at the time it is added. In particular, 073 * listeners may run in the thread that calls {@code add}. Second, the thread 074 * that calls {@link #execute} may be an internal implementation thread, such 075 * as an RPC network thread, and {@code sameThreadExecutor()} listeners may 076 * run in this thread. Finally, during the execution of a {@code 077 * sameThreadExecutor} listener, all other registered but unexecuted 078 * listeners are prevented from running, even if those listeners are to run 079 * in other executors. 080 */ 081 public void add(Runnable runnable, Executor executor) { 082 // Fail fast on a null. We throw NPE here because the contract of 083 // Executor states that it throws NPE on null listener, so we propagate 084 // that contract up into the add method as well. 085 Preconditions.checkNotNull(runnable, "Runnable was null."); 086 Preconditions.checkNotNull(executor, "Executor was null."); 087 088 // Lock while we check state. We must maintain the lock while adding the 089 // new pair so that another thread can't run the list out from under us. 090 // We only add to the list if we have not yet started execution. 091 synchronized (this) { 092 if (!executed) { 093 runnables = new RunnableExecutorPair(runnable, executor, runnables); 094 return; 095 } 096 } 097 // Execute the runnable immediately. Because of scheduling this may end up 098 // getting called before some of the previously added runnables, but we're 099 // 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}