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