001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtIncompatible; 020import com.google.common.annotations.J2ktIncompatible; 021import com.google.errorprone.annotations.concurrent.GuardedBy; 022import java.util.concurrent.Executor; 023import java.util.logging.Level; 024import java.util.logging.Logger; 025import javax.annotation.CheckForNull; 026 027/** 028 * A support class for {@code ListenableFuture} implementations to manage their listeners. An 029 * instance contains a list of listeners, each with an associated {@code Executor}, and guarantees 030 * that every {@code Runnable} that is {@linkplain #add added} will be executed after {@link 031 * #execute()} is called. Any {@code Runnable} added after the call to {@code execute} is still 032 * guaranteed to execute. There is no guarantee, however, that listeners will be executed in the 033 * order that they are added. 034 * 035 * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown 036 * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception 037 * thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and logged. 038 * 039 * @author Nishant Thakkar 040 * @author Sven Mawson 041 * @since 1.0 042 */ 043@J2ktIncompatible 044@GwtIncompatible 045@ElementTypesAreNonnullByDefault 046public final class ExecutionList { 047 /** Logger to log exceptions caught when running runnables. */ 048 private static final Logger log = Logger.getLogger(ExecutionList.class.getName()); 049 050 /** 051 * The runnable, executor pairs to execute. This acts as a stack threaded through the {@link 052 * RunnableExecutorPair#next} field. 053 */ 054 @GuardedBy("this") 055 @CheckForNull 056 private RunnableExecutorPair runnables; 057 058 @GuardedBy("this") 059 private boolean executed; 060 061 /** Creates a new, empty {@link ExecutionList}. */ 062 public ExecutionList() {} 063 064 /** 065 * Adds the {@code Runnable} and accompanying {@code Executor} to the list of listeners to 066 * execute. If execution has already begun, the listener is executed immediately. 067 * 068 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 069 * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener} 070 * documentation. 071 */ 072 public void add(Runnable runnable, Executor executor) { 073 // Fail fast on a null. We throw NPE here because the contract of Executor states that it throws 074 // NPE on null listener, so we propagate that contract up into the add method as well. 075 checkNotNull(runnable, "Runnable was null."); 076 checkNotNull(executor, "Executor was null."); 077 078 // Lock while we check state. We must maintain the lock while adding the new pair so that 079 // another thread can't run the list out from under us. We only add to the list if we have not 080 // yet started execution. 081 synchronized (this) { 082 if (!executed) { 083 runnables = new RunnableExecutorPair(runnable, executor, runnables); 084 return; 085 } 086 } 087 // Execute the runnable immediately. Because of scheduling this may end up getting called before 088 // some of the previously added runnables, but we're OK with that. If we want to change the 089 // contract to guarantee ordering among runnables we'd have to modify the logic here to allow 090 // it. 091 executeListener(runnable, executor); 092 } 093 094 /** 095 * Runs this execution list, executing all existing pairs in the order they were added. However, 096 * note that listeners added after this point may be executed before those previously added, and 097 * note that the execution order of all listeners is ultimately chosen by the implementations of 098 * the supplied executors. 099 * 100 * <p>This method is idempotent. Calling it several times in parallel is semantically equivalent 101 * to calling it exactly once. 102 * 103 * @since 10.0 (present in 1.0 as {@code run}) 104 */ 105 public void execute() { 106 // Lock while we update our state so the add method above will finish adding any listeners 107 // before we start to run them. 108 RunnableExecutorPair list; 109 synchronized (this) { 110 if (executed) { 111 return; 112 } 113 executed = true; 114 list = runnables; 115 runnables = null; // allow GC to free listeners even if this stays around for a while. 116 } 117 // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are 118 // in the opposite order from how they were added so we need to reverse the list to fulfill our 119 // contract. 120 // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could 121 // drop the contract on the method that enforces this queue like behavior since depending on it 122 // is likely to be a bug anyway. 123 124 // N.B. All writes to the list and the next pointers must have happened before the above 125 // synchronized block, so we can iterate the list without the lock held here. 126 RunnableExecutorPair reversedList = null; 127 while (list != null) { 128 RunnableExecutorPair tmp = list; 129 list = list.next; 130 tmp.next = reversedList; 131 reversedList = tmp; 132 } 133 while (reversedList != null) { 134 executeListener(reversedList.runnable, reversedList.executor); 135 reversedList = reversedList.next; 136 } 137 } 138 139 /** 140 * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain 141 * RuntimeException runtime exceptions} thrown by the executor. 142 */ 143 private static void executeListener(Runnable runnable, Executor executor) { 144 try { 145 executor.execute(runnable); 146 } catch (RuntimeException e) { 147 // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if 148 // we're given a bad one. We only catch RuntimeException because we want Errors to propagate 149 // up. 150 log.log( 151 Level.SEVERE, 152 "RuntimeException while executing runnable " + runnable + " with executor " + executor, 153 e); 154 } 155 } 156 157 private static final class RunnableExecutorPair { 158 final Runnable runnable; 159 final Executor executor; 160 @CheckForNull RunnableExecutorPair next; 161 162 RunnableExecutorPair( 163 Runnable runnable, Executor executor, @CheckForNull RunnableExecutorPair next) { 164 this.runnable = runnable; 165 this.executor = executor; 166 this.next = next; 167 } 168 } 169}