001/*
002 * Copyright (C) 2012 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.testing;
018
019import static java.util.concurrent.TimeUnit.NANOSECONDS;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.collect.ImmutableList;
024import com.google.common.primitives.Longs;
025import com.google.common.util.concurrent.AbstractFuture;
026import com.google.common.util.concurrent.AbstractListeningExecutorService;
027import com.google.common.util.concurrent.ListenableScheduledFuture;
028import com.google.common.util.concurrent.ListeningScheduledExecutorService;
029import com.google.common.util.concurrent.MoreExecutors;
030import java.util.List;
031import java.util.concurrent.Callable;
032import java.util.concurrent.Delayed;
033import java.util.concurrent.ScheduledFuture;
034import java.util.concurrent.TimeUnit;
035
036/**
037 * Factory methods for {@link ExecutorService} for testing.
038 *
039 * @author Chris Nokleberg
040 * @since 14.0
041 */
042@Beta
043@GwtIncompatible
044public final class TestingExecutors {
045  private TestingExecutors() {}
046
047  /**
048   * Returns a {@link ScheduledExecutorService} that never executes anything.
049   *
050   * <p>The {@code shutdownNow} method of the returned executor always returns an empty list despite
051   * the fact that everything is still technically awaiting execution. The {@code getDelay} method
052   * of any {@link ScheduledFuture} returned by the executor will always return the max long value
053   * instead of the time until the user-specified delay.
054   */
055  public static ListeningScheduledExecutorService noOpScheduledExecutor() {
056    return new NoOpScheduledExecutorService();
057  }
058
059  /**
060   * Creates a scheduled executor service that runs each task in the thread that invokes {@code
061   * execute/submit/schedule}, as in {@link CallerRunsPolicy}. This applies both to individually
062   * submitted tasks and to collections of tasks submitted via {@code invokeAll}, {@code invokeAny},
063   * {@code schedule}, {@code scheduleAtFixedRate}, and {@code scheduleWithFixedDelay}. In the case
064   * of tasks submitted by {@code invokeAll} or {@code invokeAny}, tasks will run serially on the
065   * calling thread. Tasks are run to completion before a {@code Future} is returned to the caller
066   * (unless the executor has been shutdown).
067   *
068   * <p>The returned executor is backed by the executor returned by {@link
069   * MoreExecutors#newDirectExecutorService} and subject to the same constraints.
070   *
071   * <p>Although all tasks are immediately executed in the thread that submitted the task, this
072   * {@code ExecutorService} imposes a small locking overhead on each task submission in order to
073   * implement shutdown and termination behavior.
074   *
075   * <p>Because of the nature of single-thread execution, the methods {@code scheduleAtFixedRate}
076   * and {@code scheduleWithFixedDelay} are not supported by this class and will throw an
077   * UnsupportedOperationException.
078   *
079   * <p>The implementation deviates from the {@code ExecutorService} specification with regards to
080   * the {@code shutdownNow} method. First, "best-effort" with regards to canceling running tasks is
081   * implemented as "no-effort". No interrupts or other attempts are made to stop threads executing
082   * tasks. Second, the returned list will always be empty, as any submitted task is considered to
083   * have started execution. This applies also to tasks given to {@code invokeAll} or {@code
084   * invokeAny} which are pending serial execution, even the subset of the tasks that have not yet
085   * started execution. It is unclear from the {@code ExecutorService} specification if these should
086   * be included, and it's much easier to implement the interpretation that they not be. Finally, a
087   * call to {@code shutdown} or {@code shutdownNow} may result in concurrent calls to {@code
088   * invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the tasks may
089   * already have been executed.
090   *
091   * @since 15.0
092   */
093  public static SameThreadScheduledExecutorService sameThreadScheduledExecutor() {
094    return new SameThreadScheduledExecutorService();
095  }
096
097  private static final class NoOpScheduledExecutorService extends AbstractListeningExecutorService
098      implements ListeningScheduledExecutorService {
099
100    private volatile boolean shutdown;
101
102    @Override
103    public void shutdown() {
104      shutdown = true;
105    }
106
107    @Override
108    public List<Runnable> shutdownNow() {
109      shutdown();
110      return ImmutableList.of();
111    }
112
113    @Override
114    public boolean isShutdown() {
115      return shutdown;
116    }
117
118    @Override
119    public boolean isTerminated() {
120      return shutdown;
121    }
122
123    @Override
124    public boolean awaitTermination(long timeout, TimeUnit unit) {
125      return true;
126    }
127
128    @Override
129    public void execute(Runnable runnable) {}
130
131    @Override
132    public <V> ListenableScheduledFuture<V> schedule(
133        Callable<V> callable, long delay, TimeUnit unit) {
134      return NeverScheduledFuture.create();
135    }
136
137    @Override
138    public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
139      return NeverScheduledFuture.create();
140    }
141
142    @Override
143    public ListenableScheduledFuture<?> scheduleAtFixedRate(
144        Runnable command, long initialDelay, long period, TimeUnit unit) {
145      return NeverScheduledFuture.create();
146    }
147
148    @Override
149    public ListenableScheduledFuture<?> scheduleWithFixedDelay(
150        Runnable command, long initialDelay, long delay, TimeUnit unit) {
151      return NeverScheduledFuture.create();
152    }
153
154    private static class NeverScheduledFuture<V> extends AbstractFuture<V>
155        implements ListenableScheduledFuture<V> {
156
157      static <V> NeverScheduledFuture<V> create() {
158        return new NeverScheduledFuture<>();
159      }
160
161      @Override
162      public long getDelay(TimeUnit unit) {
163        return Long.MAX_VALUE;
164      }
165
166      @Override
167      public int compareTo(Delayed other) {
168        return Longs.compare(getDelay(NANOSECONDS), other.getDelay(NANOSECONDS));
169      }
170    }
171  }
172}