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;
021import com.google.common.collect.Lists;
022
023import java.util.Queue;
024import java.util.concurrent.Executor;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028/**
029 * <p>A list of listeners, each with an associated {@code Executor}, that
030 * guarantees that every {@code Runnable} that is {@linkplain #add added} will
031 * be executed after {@link #execute()} is called. Any {@code Runnable} added
032 * after the call to {@code execute} is still guaranteed to execute. There is no
033 * guarantee, however, that listeners will be executed in the order that they
034 * are added.
035 *
036 * <p>Exceptions thrown by a listener will be propagated up to the executor.
037 * Any exception thrown during {@code Executor.execute} (e.g., a {@code
038 * RejectedExecutionException} or an exception thrown by {@linkplain
039 * MoreExecutors#sameThreadExecutor inline execution}) will be caught and
040 * logged.
041 *
042 * @author Nishant Thakkar
043 * @author Sven Mawson
044 * @since 1.0
045 */
046public final class ExecutionList {
047
048  // Logger to log exceptions caught when running runnables.
049  @VisibleForTesting static final Logger log =
050      Logger.getLogger(ExecutionList.class.getName());
051
052  // The runnable,executor pairs to execute.
053  private final Queue<RunnableExecutorPair> runnables = Lists.newLinkedList();
054
055  // Boolean we use mark when execution has started.  Only accessed from within
056  // synchronized blocks.
057  private boolean executed = false;
058
059  /** Creates a new, empty {@link ExecutionList}. */
060  public ExecutionList() {
061  }
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    boolean executeImmediate = false;
089
090    // Lock while we check state.  We must maintain the lock while adding the
091    // new pair so that another thread can't run the list out from under us.
092    // We only add to the list if we have not yet started execution.
093    synchronized (runnables) {
094      if (!executed) {
095        runnables.add(new RunnableExecutorPair(runnable, executor));
096      } else {
097        executeImmediate = true;
098      }
099    }
100
101    // Execute the runnable immediately. Because of scheduling this may end up
102    // getting called before some of the previously added runnables, but we're
103    // OK with that.  If we want to change the contract to guarantee ordering
104    // among runnables we'd have to modify the logic here to allow it.
105    if (executeImmediate) {
106      new RunnableExecutorPair(runnable, executor).execute();
107    }
108  }
109
110  /**
111   * Runs this execution list, executing all existing pairs in the order they
112   * were added. However, note that listeners added after this point may be
113   * executed before those previously added, and note that the execution order
114   * of all listeners is ultimately chosen by the implementations of the
115   * supplied executors.
116   *
117   * <p>This method is idempotent. Calling it several times in parallel is
118   * semantically equivalent to calling it exactly once.
119   *
120   * @since 10.0 (present in 1.0 as {@code run})
121   */
122  public void execute() {
123    // Lock while we update our state so the add method above will finish adding
124    // any listeners before we start to run them.
125    synchronized (runnables) {
126      if (executed) {
127        return;
128      }
129      executed = true;
130    }
131
132    // At this point the runnables will never be modified by another
133    // thread, so we are safe using it outside of the synchronized block.
134    while (!runnables.isEmpty()) {
135      runnables.poll().execute();
136    }
137  }
138
139  private static class RunnableExecutorPair {
140    final Runnable runnable;
141    final Executor executor;
142
143    RunnableExecutorPair(Runnable runnable, Executor executor) {
144      this.runnable = runnable;
145      this.executor = executor;
146    }
147
148    void execute() {
149      try {
150        executor.execute(runnable);
151      } catch (RuntimeException e) {
152        // Log it and keep going, bad runnable and/or executor.  Don't
153        // punish the other runnables if we're given a bad one.  We only
154        // catch RuntimeException because we want Errors to propagate up.
155        log.log(Level.SEVERE, "RuntimeException while executing runnable "
156            + runnable + " with executor " + executor, e);
157      }
158    }
159  }
160}