Debian Codegraph @

guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java

raw
1 /*
2 * Copyright (C) 2012 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.util.concurrent.testing;
18
19 import static java.util.concurrent.TimeUnit.NANOSECONDS;
20
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtIncompatible;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.primitives.Longs;
25 import com.google.common.util.concurrent.AbstractFuture;
26 import com.google.common.util.concurrent.AbstractListeningExecutorService;
27 import com.google.common.util.concurrent.ListenableScheduledFuture;
28 import com.google.common.util.concurrent.ListeningScheduledExecutorService;
29 import com.google.common.util.concurrent.MoreExecutors;
30 import java.util.List;
31 import java.util.concurrent.Callable;
32 import java.util.concurrent.Delayed;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.ScheduledFuture;
36 import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
37 import java.util.concurrent.TimeUnit;
38
39 /**
40 * Factory methods for {@link ExecutorService} for testing.
41 *
42 * @author Chris Nokleberg
43 * @since 14.0
44 */
45 @GwtIncompatible
46 public final class TestingExecutors {
47 private TestingExecutors() {}
48
49 /**
50 * Returns a {@link ScheduledExecutorService} that never executes anything.
51 *
52 * <p>The {@code shutdownNow} method of the returned executor always returns an empty list despite
53 * the fact that everything is still technically awaiting execution. The {@code getDelay} method
54 * of any {@link ScheduledFuture} returned by the executor will always return the max long value
55 * instead of the time until the user-specified delay.
56 */
57 public static ListeningScheduledExecutorService noOpScheduledExecutor() {
58 return new NoOpScheduledExecutorService();
59 }
60
61 /**
62 * Creates a scheduled executor service that runs each task in the thread that invokes {@code
63 * execute/submit/schedule}, as in {@link CallerRunsPolicy}. This applies both to individually
64 * submitted tasks and to collections of tasks submitted via {@code invokeAll}, {@code invokeAny},
65 * {@code schedule}, {@code scheduleAtFixedRate}, and {@code scheduleWithFixedDelay}. In the case
66 * of tasks submitted by {@code invokeAll} or {@code invokeAny}, tasks will run serially on the
67 * calling thread. Tasks are run to completion before a {@code Future} is returned to the caller
68 * (unless the executor has been shutdown).
69 *
70 * <p>The returned executor is backed by the executor returned by {@link
71 * MoreExecutors#newDirectExecutorService} and subject to the same constraints.
72 *
73 * <p>Although all tasks are immediately executed in the thread that submitted the task, this
74 * {@code ExecutorService} imposes a small locking overhead on each task submission in order to
75 * implement shutdown and termination behavior.
76 *
77 * <p>Because of the nature of single-thread execution, the methods {@code scheduleAtFixedRate}
78 * and {@code scheduleWithFixedDelay} are not supported by this class and will throw an
79 * UnsupportedOperationException.
80 *
81 * <p>The implementation deviates from the {@code ExecutorService} specification with regards to
82 * the {@code shutdownNow} method. First, "best-effort" with regards to canceling running tasks is
83 * implemented as "no-effort". No interrupts or other attempts are made to stop threads executing
84 * tasks. Second, the returned list will always be empty, as any submitted task is considered to
85 * have started execution. This applies also to tasks given to {@code invokeAll} or {@code
86 * invokeAny} which are pending serial execution, even the subset of the tasks that have not yet
87 * started execution. It is unclear from the {@code ExecutorService} specification if these should
88 * be included, and it's much easier to implement the interpretation that they not be. Finally, a
89 * call to {@code shutdown} or {@code shutdownNow} may result in concurrent calls to {@code
90 * invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the tasks may
91 * already have been executed.
92 *
93 * @since 32.0.0 (taking the place of a method with a different return type from 15.0)
94 */
95 @Beta
96 public static ListeningScheduledExecutorService sameThreadScheduledExecutor() {
97 return new SameThreadScheduledExecutorService();
98 }
99
100 private static final class NoOpScheduledExecutorService extends AbstractListeningExecutorService
101 implements ListeningScheduledExecutorService {
102
103 private volatile boolean shutdown;
104
105 @Override
106 public void shutdown() {
107 shutdown = true;
108 }
109
110 @Override
111 public List<Runnable> shutdownNow() {
112 shutdown();
113 return ImmutableList.of();
114 }
115
116 @Override
117 public boolean isShutdown() {
118 return shutdown;
119 }
120
121 @Override
122 public boolean isTerminated() {
123 return shutdown;
124 }
125
126 @Override
127 public boolean awaitTermination(long timeout, TimeUnit unit) {
128 return true;
129 }
130
131 @Override
132 public void execute(Runnable runnable) {}
133
134 @Override
135 public <V> ListenableScheduledFuture<V> schedule(
136 Callable<V> callable, long delay, TimeUnit unit) {
137 return NeverScheduledFuture.create();
138 }
139
140 @Override
141 public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
142 return NeverScheduledFuture.create();
143 }
144
145 @Override
146 public ListenableScheduledFuture<?> scheduleAtFixedRate(
147 Runnable command, long initialDelay, long period, TimeUnit unit) {
148 return NeverScheduledFuture.create();
149 }
150
151 @Override
152 public ListenableScheduledFuture<?> scheduleWithFixedDelay(
153 Runnable command, long initialDelay, long delay, TimeUnit unit) {
154 return NeverScheduledFuture.create();
155 }
156
157 private static class NeverScheduledFuture<V> extends AbstractFuture<V>
158 implements ListenableScheduledFuture<V> {
159
160 static <V> NeverScheduledFuture<V> create() {
161 return new NeverScheduledFuture<>();
162 }
163
164 @Override
165 public long getDelay(TimeUnit unit) {
166 return Long.MAX_VALUE;
167 }
168
169 @Override
170 public int compareTo(Delayed other) {
171 return Longs.compare(getDelay(NANOSECONDS), other.getDelay(NANOSECONDS));
172 }
173 }
174 }
175 }