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    
017    package com.google.common.util.concurrent;
018    
019    import com.google.common.annotations.Beta;
020    import com.google.common.base.Preconditions;
021    import com.google.common.collect.Lists;
022    
023    import java.util.Queue;
024    import java.util.concurrent.Executor;
025    import java.util.logging.Level;
026    import 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     */
046    public final class ExecutionList {
047    
048      // Logger to log exceptions caught when running runnables.
049      private 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 Future} is
072       * done at the time it is added. In particular, if added late, listeners will
073       * run in the thread that called {@code add}. Second, listeners may run in an
074       * internal thread of the system responsible for the input {@code Future},
075       * such as an RPC network thread. Finally, during the execution of a {@link
076       * MoreExecutors#sameThreadExecutor sameThreadExecutor} listener, all other
077       * registered but unexecuted listeners are prevented from running, even if
078       * those listeners are to run in other executors.
079       */
080      public void add(Runnable runnable, Executor executor) {
081        // Fail fast on a null.  We throw NPE here because the contract of
082        // Executor states that it throws NPE on null listener, so we propagate
083        // that contract up into the add method as well.
084        Preconditions.checkNotNull(runnable, "Runnable was null.");
085        Preconditions.checkNotNull(executor, "Executor was null.");
086    
087        boolean executeImmediate = false;
088    
089        // Lock while we check state.  We must maintain the lock while adding the
090        // new pair so that another thread can't run the list out from under us.
091        // We only add to the list if we have not yet started execution.
092        synchronized (runnables) {
093          if (!executed) {
094            runnables.add(new RunnableExecutorPair(runnable, executor));
095          } else {
096            executeImmediate = true;
097          }
098        }
099    
100        // Execute the runnable immediately. Because of scheduling this may end up
101        // getting called before some of the previously added runnables, but we're
102        // OK with that.  If we want to change the contract to guarantee ordering
103        // among runnables we'd have to modify the logic here to allow it.
104        if (executeImmediate) {
105          new RunnableExecutorPair(runnable, executor).execute();
106        }
107      }
108    
109      /**
110       * Equivalent to {@link #execute}.
111       *
112       * @deprecated Use {@link #execute}. This method will be removed in Guava
113       * release 11.
114       */
115      @Beta @Deprecated
116      public
117      void run() {
118        execute();
119      }
120    
121      /**
122       * Runs this execution list, executing all existing pairs in the order they
123       * were added. However, note that listeners added after this point may be
124       * executed before those previously added, and note that the execution order
125       * of all listeners is ultimately chosen by the implementations of the
126       * supplied executors.
127       *
128       * <p>This method is idempotent. Calling it several times in parallel is
129       * semantically equivalent to calling it exactly once.
130       *
131       * @since 10.0 (present in 1.0 as {@code run})
132       */
133      public void execute() {
134        // Lock while we update our state so the add method above will finish adding
135        // any listeners before we start to run them.
136        synchronized (runnables) {
137          if (executed) {
138            return;
139          }
140          executed = true;
141        }
142    
143        // At this point the runnables will never be modified by another
144        // thread, so we are safe using it outside of the synchronized block.
145        while (!runnables.isEmpty()) {
146          runnables.poll().execute();
147        }
148      }
149    
150      private static class RunnableExecutorPair {
151        final Runnable runnable;
152        final Executor executor;
153    
154        RunnableExecutorPair(Runnable runnable, Executor executor) {
155          this.runnable = runnable;
156          this.executor = executor;
157        }
158    
159        void execute() {
160          try {
161            executor.execute(runnable);
162          } catch (RuntimeException e) {
163            // Log it and keep going, bad runnable and/or executor.  Don't
164            // punish the other runnables if we're given a bad one.  We only
165            // catch RuntimeException because we want Errors to propagate up.
166            log.log(Level.SEVERE, "RuntimeException while executing runnable "
167                + runnable + " with executor " + executor, e);
168          }
169        }
170      }
171    }