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.errorprone.annotations.concurrent.GuardedBy;
021import java.util.concurrent.Executor;
022import java.util.logging.Level;
023import java.util.logging.Logger;
024import org.checkerframework.checker.nullness.compatqual.NullableDecl;
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@GwtIncompatible
043public final class ExecutionList {
044  /** Logger to log exceptions caught when running runnables. */
045  private static final Logger log = Logger.getLogger(ExecutionList.class.getName());
046
047  /**
048   * The runnable, executor pairs to execute. This acts as a stack threaded through the {@link
049   * RunnableExecutorPair#next} field.
050   */
051  @GuardedBy("this")
052  @NullableDecl
053  private RunnableExecutorPair runnables;
054
055  @GuardedBy("this")
056  private boolean executed;
057
058  /** Creates a new, empty {@link ExecutionList}. */
059  public ExecutionList() {}
060
061  /**
062   * Adds the {@code Runnable} and accompanying {@code Executor} to the list of listeners to
063   * execute. If execution has already begun, the listener is executed immediately.
064   *
065   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
066   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
067   * documentation.
068   */
069  public void add(Runnable runnable, Executor executor) {
070    // Fail fast on a null. We throw NPE here because the contract of Executor states that it throws
071    // NPE on null listener, so we propagate that contract up into the add method as well.
072    checkNotNull(runnable, "Runnable was null.");
073    checkNotNull(executor, "Executor was null.");
074
075    // Lock while we check state. We must maintain the lock while adding the new pair so that
076    // another thread can't run the list out from under us. We only add to the list if we have not
077    // yet started execution.
078    synchronized (this) {
079      if (!executed) {
080        runnables = new RunnableExecutorPair(runnable, executor, runnables);
081        return;
082      }
083    }
084    // Execute the runnable immediately. Because of scheduling this may end up getting called before
085    // some of the previously added runnables, but we're OK with that. If we want to change the
086    // contract to guarantee ordering among runnables we'd have to modify the logic here to allow
087    // it.
088    executeListener(runnable, executor);
089  }
090
091  /**
092   * Runs this execution list, executing all existing pairs in the order they were added. However,
093   * note that listeners added after this point may be executed before those previously added, and
094   * note that the execution order of all listeners is ultimately chosen by the implementations of
095   * the supplied executors.
096   *
097   * <p>This method is idempotent. Calling it several times in parallel is semantically equivalent
098   * to calling it exactly once.
099   *
100   * @since 10.0 (present in 1.0 as {@code run})
101   */
102  public void execute() {
103    // Lock while we update our state so the add method above will finish adding any listeners
104    // before we start to run them.
105    RunnableExecutorPair list;
106    synchronized (this) {
107      if (executed) {
108        return;
109      }
110      executed = true;
111      list = runnables;
112      runnables = null; // allow GC to free listeners even if this stays around for a while.
113    }
114    // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are
115    // in the opposite order from how they were added so we need to reverse the list to fulfill our
116    // contract.
117    // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could
118    // drop the contract on the method that enforces this queue like behavior since depending on it
119    // is likely to be a bug anyway.
120
121    // N.B. All writes to the list and the next pointers must have happened before the above
122    // synchronized block, so we can iterate the list without the lock held here.
123    RunnableExecutorPair reversedList = null;
124    while (list != null) {
125      RunnableExecutorPair tmp = list;
126      list = list.next;
127      tmp.next = reversedList;
128      reversedList = tmp;
129    }
130    while (reversedList != null) {
131      executeListener(reversedList.runnable, reversedList.executor);
132      reversedList = reversedList.next;
133    }
134  }
135
136  /**
137   * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain
138   * RuntimeException runtime exceptions} thrown by the executor.
139   */
140  private static void executeListener(Runnable runnable, Executor executor) {
141    try {
142      executor.execute(runnable);
143    } catch (RuntimeException e) {
144      // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if
145      // we're given a bad one. We only catch RuntimeException because we want Errors to propagate
146      // up.
147      log.log(
148          Level.SEVERE,
149          "RuntimeException while executing runnable " + runnable + " with executor " + executor,
150          e);
151    }
152  }
153
154  private static final class RunnableExecutorPair {
155    final Runnable runnable;
156    final Executor executor;
157    @NullableDecl RunnableExecutorPair next;
158
159    RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
160      this.runnable = runnable;
161      this.executor = executor;
162      this.next = next;
163    }
164  }
165}