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 javax.annotation.CheckForNull;
025
026/**
027 * A support class for {@code ListenableFuture} implementations to manage their listeners. An
028 * instance contains a list of listeners, each with an associated {@code Executor}, and guarantees
029 * that every {@code Runnable} that is {@linkplain #add added} will be executed after {@link
030 * #execute()} is called. Any {@code Runnable} added after the call to {@code execute} is still
031 * guaranteed to execute. There is no guarantee, however, that listeners will be executed in the
032 * order that they are added.
033 *
034 * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
035 * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
036 * thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and logged.
037 *
038 * @author Nishant Thakkar
039 * @author Sven Mawson
040 * @since 1.0
041 */
042@J2ktIncompatible
043@GwtIncompatible
044@ElementTypesAreNonnullByDefault
045public final class ExecutionList {
046  /** Logger to log exceptions caught when running runnables. */
047  private static final LazyLogger log = new LazyLogger(ExecutionList.class);
048
049  /**
050   * The runnable, executor pairs to execute. This acts as a stack threaded through the {@link
051   * RunnableExecutorPair#next} field.
052   */
053  @GuardedBy("this")
054  @CheckForNull
055  private RunnableExecutorPair runnables;
056
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 listeners to
065   * execute. If execution has already begun, the listener is executed immediately.
066   *
067   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
068   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
069   * documentation.
070   */
071  public void add(Runnable runnable, Executor executor) {
072    // Fail fast on a null. We throw NPE here because the contract of Executor states that it throws
073    // NPE on null listener, so we propagate that contract up into the add method as well.
074    checkNotNull(runnable, "Runnable was null.");
075    checkNotNull(executor, "Executor was null.");
076
077    // Lock while we check state. We must maintain the lock while adding the new pair so that
078    // another thread can't run the list out from under us. We only add to the list if we have not
079    // yet started execution.
080    synchronized (this) {
081      if (!executed) {
082        runnables = new RunnableExecutorPair(runnable, executor, runnables);
083        return;
084      }
085    }
086    // Execute the runnable immediately. Because of scheduling this may end up getting called before
087    // some of the previously added runnables, but we're OK with that. If we want to change the
088    // contract to guarantee ordering among runnables we'd have to modify the logic here to allow
089    // it.
090    executeListener(runnable, executor);
091  }
092
093  /**
094   * Runs this execution list, executing all existing pairs in the order they were added. However,
095   * note that listeners added after this point may be executed before those previously added, and
096   * note that the execution order of all listeners is ultimately chosen by the implementations of
097   * the supplied executors.
098   *
099   * <p>This method is idempotent. Calling it several times in parallel is semantically equivalent
100   * to calling it exactly once.
101   *
102   * @since 10.0 (present in 1.0 as {@code run})
103   */
104  public void execute() {
105    // Lock while we update our state so the add method above will finish adding any listeners
106    // before we start to run them.
107    RunnableExecutorPair list;
108    synchronized (this) {
109      if (executed) {
110        return;
111      }
112      executed = true;
113      list = runnables;
114      runnables = null; // allow GC to free listeners even if this stays around for a while.
115    }
116    // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are
117    // in the opposite order from how they were added so we need to reverse the list to fulfill our
118    // contract.
119    // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could
120    // drop the contract on the method that enforces this queue like behavior since depending on it
121    // is likely to be a bug anyway.
122
123    // N.B. All writes to the list and the next pointers must have happened before the above
124    // synchronized block, so we can iterate the list without the lock held here.
125    RunnableExecutorPair reversedList = null;
126    while (list != null) {
127      RunnableExecutorPair tmp = list;
128      list = list.next;
129      tmp.next = reversedList;
130      reversedList = tmp;
131    }
132    while (reversedList != null) {
133      executeListener(reversedList.runnable, reversedList.executor);
134      reversedList = reversedList.next;
135    }
136  }
137
138  /**
139   * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain
140   * RuntimeException runtime exceptions} thrown by the executor.
141   */
142  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
143  private static void executeListener(Runnable runnable, Executor executor) {
144    try {
145      executor.execute(runnable);
146    } catch (Exception e) { // sneaky checked exception
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.get()
151          .log(
152              Level.SEVERE,
153              "RuntimeException while executing runnable "
154                  + runnable
155                  + " with executor "
156                  + executor,
157              e);
158    }
159  }
160
161  private static final class RunnableExecutorPair {
162    final Runnable runnable;
163    final Executor executor;
164    @CheckForNull RunnableExecutorPair next;
165
166    RunnableExecutorPair(
167        Runnable runnable, Executor executor, @CheckForNull RunnableExecutorPair next) {
168      this.runnable = runnable;
169      this.executor = executor;
170      this.next = next;
171    }
172  }
173}