001/*
002 * Copyright (C) 2006 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.util.concurrent.Internal.saturatedToNanos;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import java.time.Duration;
023import java.util.concurrent.Callable;
024import java.util.concurrent.ExecutionException;
025import java.util.concurrent.TimeUnit;
026import java.util.concurrent.TimeoutException;
027
028/**
029 * Imposes a time limit on method calls.
030 *
031 * @author Kevin Bourrillion
032 * @author Jens Nyman
033 * @since 1.0
034 */
035@Beta
036@GwtIncompatible
037public interface TimeLimiter {
038
039  /**
040   * Returns an instance of {@code interfaceType} that delegates all method calls to the {@code
041   * target} object, enforcing the specified time limit on each call. This time-limited delegation
042   * is also performed for calls to {@link Object#equals}, {@link Object#hashCode}, and {@link
043   * Object#toString}.
044   *
045   * <p>If the target method call finishes before the limit is reached, the return value or
046   * exception is propagated to the caller exactly as-is. If, on the other hand, the time limit is
047   * reached, the proxy will attempt to abort the call to the target, and will throw an {@link
048   * UncheckedTimeoutException} to the caller.
049   *
050   * <p>It is important to note that the primary purpose of the proxy object is to return control to
051   * the caller when the timeout elapses; aborting the target method call is of secondary concern.
052   * The particular nature and strength of the guarantees made by the proxy is
053   * implementation-dependent. However, it is important that each of the methods on the target
054   * object behaves appropriately when its thread is interrupted.
055   *
056   * <p>For example, to return the value of {@code target.someMethod()}, but substitute {@code
057   * DEFAULT_VALUE} if this method call takes over 50 ms, you can use this code:
058   *
059   * <pre>
060   *   TimeLimiter limiter = . . .;
061   *   TargetType proxy = limiter.newProxy(
062   *       target, TargetType.class, 50, TimeUnit.MILLISECONDS);
063   *   try {
064   *     return proxy.someMethod();
065   *   } catch (UncheckedTimeoutException e) {
066   *     return DEFAULT_VALUE;
067   *   }
068   * </pre>
069   *
070   * @param target the object to proxy
071   * @param interfaceType the interface you wish the returned proxy to implement
072   * @param timeoutDuration with timeoutUnit, the maximum length of time that callers are willing to
073   *     wait on each method call to the proxy
074   * @param timeoutUnit with timeoutDuration, the maximum length of time that callers are willing to
075   *     wait on each method call to the proxy
076   * @return a time-limiting proxy
077   * @throws IllegalArgumentException if {@code interfaceType} is a regular class, enum, or
078   *     annotation type, rather than an interface
079   */
080  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
081  <T> T newProxy(T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit);
082
083  /**
084   * Returns an instance of {@code interfaceType} that delegates all method calls to the {@code
085   * target} object, enforcing the specified time limit on each call. This time-limited delegation
086   * is also performed for calls to {@link Object#equals}, {@link Object#hashCode}, and {@link
087   * Object#toString}.
088   *
089   * <p>If the target method call finishes before the limit is reached, the return value or
090   * exception is propagated to the caller exactly as-is. If, on the other hand, the time limit is
091   * reached, the proxy will attempt to abort the call to the target, and will throw an {@link
092   * UncheckedTimeoutException} to the caller.
093   *
094   * <p>It is important to note that the primary purpose of the proxy object is to return control to
095   * the caller when the timeout elapses; aborting the target method call is of secondary concern.
096   * The particular nature and strength of the guarantees made by the proxy is
097   * implementation-dependent. However, it is important that each of the methods on the target
098   * object behaves appropriately when its thread is interrupted.
099   *
100   * <p>For example, to return the value of {@code target.someMethod()}, but substitute {@code
101   * DEFAULT_VALUE} if this method call takes over 50 ms, you can use this code:
102   *
103   * <pre>
104   *   TimeLimiter limiter = . . .;
105   *   TargetType proxy = limiter.newProxy(target, TargetType.class, Duration.ofMillis(50));
106   *   try {
107   *     return proxy.someMethod();
108   *   } catch (UncheckedTimeoutException e) {
109   *     return DEFAULT_VALUE;
110   *   }
111   * </pre>
112   *
113   * @param target the object to proxy
114   * @param interfaceType the interface you wish the returned proxy to implement
115   * @param timeout the maximum length of time that callers are willing to wait on each method call
116   *     to the proxy
117   * @return a time-limiting proxy
118   * @throws IllegalArgumentException if {@code interfaceType} is a regular class, enum, or
119   *     annotation type, rather than an interface
120   * @since 28.0
121   */
122  default <T> T newProxy(T target, Class<T> interfaceType, Duration timeout) {
123    return newProxy(target, interfaceType, saturatedToNanos(timeout), TimeUnit.NANOSECONDS);
124  }
125
126  /**
127   * Invokes a specified Callable, timing out after the specified time limit. If the target method
128   * call finishes before the limit is reached, the return value or a wrapped exception is
129   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the call to
130   * the target, and throw a {@link TimeoutException} to the caller.
131   *
132   * @param callable the Callable to execute
133   * @param timeoutDuration with timeoutUnit, the maximum length of time to wait
134   * @param timeoutUnit with timeoutDuration, the maximum length of time to wait
135   * @return the result returned by the Callable
136   * @throws TimeoutException if the time limit is reached
137   * @throws InterruptedException if the current thread was interrupted during execution
138   * @throws ExecutionException if {@code callable} throws a checked exception
139   * @throws UncheckedExecutionException if {@code callable} throws a {@code RuntimeException}
140   * @throws ExecutionError if {@code callable} throws an {@code Error}
141   * @since 22.0
142   */
143  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
144  @CanIgnoreReturnValue
145  <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
146      throws TimeoutException, InterruptedException, ExecutionException;
147
148  /**
149   * Invokes a specified Callable, timing out after the specified time limit. If the target method
150   * call finishes before the limit is reached, the return value or a wrapped exception is
151   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the call to
152   * the target, and throw a {@link TimeoutException} to the caller.
153   *
154   * @param callable the Callable to execute
155   * @param timeout the maximum length of time to wait
156   * @return the result returned by the Callable
157   * @throws TimeoutException if the time limit is reached
158   * @throws InterruptedException if the current thread was interrupted during execution
159   * @throws ExecutionException if {@code callable} throws a checked exception
160   * @throws UncheckedExecutionException if {@code callable} throws a {@code RuntimeException}
161   * @throws ExecutionError if {@code callable} throws an {@code Error}
162   * @since 28.0
163   */
164  @CanIgnoreReturnValue
165  default <T> T callWithTimeout(Callable<T> callable, Duration timeout)
166      throws TimeoutException, InterruptedException, ExecutionException {
167    return callWithTimeout(callable, saturatedToNanos(timeout), TimeUnit.NANOSECONDS);
168  }
169
170  /**
171   * Invokes a specified Callable, timing out after the specified time limit. If the target method
172   * call finishes before the limit is reached, the return value or a wrapped exception is
173   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the call to
174   * the target, and throw a {@link TimeoutException} to the caller.
175   *
176   * <p>The difference with {@link #callWithTimeout(Callable, long, TimeUnit)} is that this method
177   * will ignore interrupts on the current thread.
178   *
179   * @param callable the Callable to execute
180   * @param timeoutDuration with timeoutUnit, the maximum length of time to wait
181   * @param timeoutUnit with timeoutDuration, the maximum length of time to wait
182   * @return the result returned by the Callable
183   * @throws TimeoutException if the time limit is reached
184   * @throws ExecutionException if {@code callable} throws a checked exception
185   * @throws UncheckedExecutionException if {@code callable} throws a {@code RuntimeException}
186   * @throws ExecutionError if {@code callable} throws an {@code Error}
187   * @since 22.0
188   */
189  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
190  @CanIgnoreReturnValue
191  <T> T callUninterruptiblyWithTimeout(
192      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
193      throws TimeoutException, ExecutionException;
194
195  /**
196   * Invokes a specified Callable, timing out after the specified time limit. If the target method
197   * call finishes before the limit is reached, the return value or a wrapped exception is
198   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the call to
199   * the target, and throw a {@link TimeoutException} to the caller.
200   *
201   * <p>The difference with {@link #callWithTimeout(Callable, Duration)} is that this method will
202   * ignore interrupts on the current thread.
203   *
204   * @param callable the Callable to execute
205   * @param timeout the maximum length of time to wait
206   * @return the result returned by the Callable
207   * @throws TimeoutException if the time limit is reached
208   * @throws ExecutionException if {@code callable} throws a checked exception
209   * @throws UncheckedExecutionException if {@code callable} throws a {@code RuntimeException}
210   * @throws ExecutionError if {@code callable} throws an {@code Error}
211   * @since 28.0
212   */
213  @CanIgnoreReturnValue
214  default <T> T callUninterruptiblyWithTimeout(Callable<T> callable, Duration timeout)
215      throws TimeoutException, ExecutionException {
216    return callUninterruptiblyWithTimeout(
217        callable, saturatedToNanos(timeout), TimeUnit.NANOSECONDS);
218  }
219
220  /**
221   * Invokes a specified Runnable, timing out after the specified time limit. If the target method
222   * run finishes before the limit is reached, this method returns or a wrapped exception is
223   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the run, and
224   * throw a {@link TimeoutException} to the caller.
225   *
226   * @param runnable the Runnable to execute
227   * @param timeoutDuration with timeoutUnit, the maximum length of time to wait
228   * @param timeoutUnit with timeoutDuration, the maximum length of time to wait
229   * @throws TimeoutException if the time limit is reached
230   * @throws InterruptedException if the current thread was interrupted during execution
231   * @throws UncheckedExecutionException if {@code runnable} throws a {@code RuntimeException}
232   * @throws ExecutionError if {@code runnable} throws an {@code Error}
233   * @since 22.0
234   */
235  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
236  void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
237      throws TimeoutException, InterruptedException;
238
239  /**
240   * Invokes a specified Runnable, timing out after the specified time limit. If the target method
241   * run finishes before the limit is reached, this method returns or a wrapped exception is
242   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the run, and
243   * throw a {@link TimeoutException} to the caller.
244   *
245   * @param runnable the Runnable to execute
246   * @param timeout the maximum length of time to wait
247   * @throws TimeoutException if the time limit is reached
248   * @throws InterruptedException if the current thread was interrupted during execution
249   * @throws UncheckedExecutionException if {@code runnable} throws a {@code RuntimeException}
250   * @throws ExecutionError if {@code runnable} throws an {@code Error}
251   * @since 28.0
252   */
253  default void runWithTimeout(Runnable runnable, Duration timeout)
254      throws TimeoutException, InterruptedException {
255    runWithTimeout(runnable, saturatedToNanos(timeout), TimeUnit.NANOSECONDS);
256  }
257
258  /**
259   * Invokes a specified Runnable, timing out after the specified time limit. If the target method
260   * run finishes before the limit is reached, this method returns or a wrapped exception is
261   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the run, and
262   * throw a {@link TimeoutException} to the caller.
263   *
264   * <p>The difference with {@link #runWithTimeout(Runnable, long, TimeUnit)} is that this method
265   * will ignore interrupts on the current thread.
266   *
267   * @param runnable the Runnable to execute
268   * @param timeoutDuration with timeoutUnit, the maximum length of time to wait
269   * @param timeoutUnit with timeoutDuration, the maximum length of time to wait
270   * @throws TimeoutException if the time limit is reached
271   * @throws UncheckedExecutionException if {@code runnable} throws a {@code RuntimeException}
272   * @throws ExecutionError if {@code runnable} throws an {@code Error}
273   * @since 22.0
274   */
275  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
276  void runUninterruptiblyWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
277      throws TimeoutException;
278
279  /**
280   * Invokes a specified Runnable, timing out after the specified time limit. If the target method
281   * run finishes before the limit is reached, this method returns or a wrapped exception is
282   * propagated. If, on the other hand, the time limit is reached, we attempt to abort the run, and
283   * throw a {@link TimeoutException} to the caller.
284   *
285   * <p>The difference with {@link #runWithTimeout(Runnable, Duration)} is that this method will
286   * ignore interrupts on the current thread.
287   *
288   * @param runnable the Runnable to execute
289   * @param timeout the maximum length of time to wait
290   * @throws TimeoutException if the time limit is reached
291   * @throws UncheckedExecutionException if {@code runnable} throws a {@code RuntimeException}
292   * @throws ExecutionError if {@code runnable} throws an {@code Error}
293   * @since 28.0
294   */
295  default void runUninterruptiblyWithTimeout(Runnable runnable, Duration timeout)
296      throws TimeoutException {
297    runUninterruptiblyWithTimeout(runnable, saturatedToNanos(timeout), TimeUnit.NANOSECONDS);
298  }
299}