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.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
020
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.annotations.J2ktIncompatible;
023import com.google.common.collect.ObjectArrays;
024import com.google.common.collect.Sets;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import java.lang.reflect.InvocationHandler;
027import java.lang.reflect.InvocationTargetException;
028import java.lang.reflect.Method;
029import java.lang.reflect.Proxy;
030import java.util.Set;
031import java.util.concurrent.Callable;
032import java.util.concurrent.ExecutionException;
033import java.util.concurrent.ExecutorService;
034import java.util.concurrent.Executors;
035import java.util.concurrent.Future;
036import java.util.concurrent.TimeUnit;
037import java.util.concurrent.TimeoutException;
038import org.jspecify.annotations.Nullable;
039
040/**
041 * A TimeLimiter that runs method calls in the background using an {@link ExecutorService}. If the
042 * time limit expires for a given method call, the thread running the call will be interrupted.
043 *
044 * @author Kevin Bourrillion
045 * @author Jens Nyman
046 * @since 1.0
047 */
048@J2ktIncompatible
049@GwtIncompatible
050// TODO: b/227335009 - Maybe change interruption behavior, but it requires thought.
051@SuppressWarnings("Interruption")
052public final class SimpleTimeLimiter implements TimeLimiter {
053
054  private final ExecutorService executor;
055
056  private SimpleTimeLimiter(ExecutorService executor) {
057    this.executor = checkNotNull(executor);
058  }
059
060  /**
061   * Creates a TimeLimiter instance using the given executor service to execute method calls.
062   *
063   * <p><b>Warning:</b> using a bounded executor may be counterproductive! If the thread pool fills
064   * up, any time callers spend waiting for a thread may count toward their time limit, and in this
065   * case the call may even time out before the target method is ever invoked.
066   *
067   * @param executor the ExecutorService that will execute the method calls on the target objects;
068   *     for example, a {@link Executors#newCachedThreadPool()}.
069   * @since 22.0
070   */
071  public static SimpleTimeLimiter create(ExecutorService executor) {
072    return new SimpleTimeLimiter(executor);
073  }
074
075  @Override
076  public <T> T newProxy(
077      T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit) {
078    checkNotNull(target);
079    checkNotNull(interfaceType);
080    checkNotNull(timeoutUnit);
081    checkPositiveTimeout(timeoutDuration);
082    checkArgument(interfaceType.isInterface(), "interfaceType must be an interface type");
083
084    Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType);
085
086    InvocationHandler handler =
087        (obj, method, args) -> {
088          Callable<@Nullable Object> callable =
089              () -> {
090                try {
091                  return method.invoke(target, args);
092                } catch (InvocationTargetException e) {
093                  throw throwCause(e, /* combineStackTraces= */ false);
094                }
095              };
096          return callWithTimeout(
097              callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method));
098        };
099    return newProxy(interfaceType, handler);
100  }
101
102  // TODO: replace with version in common.reflect if and when it's open-sourced
103  private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
104    Object object =
105        Proxy.newProxyInstance(
106            interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, handler);
107    return interfaceType.cast(object);
108  }
109
110  @ParametricNullness
111  private <T extends @Nullable Object> T callWithTimeout(
112      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
113      throws Exception {
114    checkNotNull(callable);
115    checkNotNull(timeoutUnit);
116    checkPositiveTimeout(timeoutDuration);
117
118    Future<T> future = executor.submit(callable);
119
120    try {
121      return amInterruptible
122          ? future.get(timeoutDuration, timeoutUnit)
123          : getUninterruptibly(future, timeoutDuration, timeoutUnit);
124    } catch (InterruptedException e) {
125      future.cancel(true);
126      throw e;
127    } catch (ExecutionException e) {
128      throw throwCause(e, true /* combineStackTraces */);
129    } catch (TimeoutException e) {
130      future.cancel(true);
131      throw new UncheckedTimeoutException(e);
132    }
133  }
134
135  @CanIgnoreReturnValue
136  @Override
137  @ParametricNullness
138  public <T extends @Nullable Object> T callWithTimeout(
139      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
140      throws TimeoutException, InterruptedException, ExecutionException {
141    checkNotNull(callable);
142    checkNotNull(timeoutUnit);
143    checkPositiveTimeout(timeoutDuration);
144
145    Future<T> future = executor.submit(callable);
146
147    try {
148      return future.get(timeoutDuration, timeoutUnit);
149    } catch (InterruptedException | TimeoutException e) {
150      future.cancel(true /* mayInterruptIfRunning */);
151      throw e;
152    } catch (ExecutionException e) {
153      wrapAndThrowExecutionExceptionOrError(e.getCause());
154      throw new AssertionError();
155    }
156  }
157
158  @CanIgnoreReturnValue
159  @Override
160  @ParametricNullness
161  public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
162      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
163      throws TimeoutException, ExecutionException {
164    checkNotNull(callable);
165    checkNotNull(timeoutUnit);
166    checkPositiveTimeout(timeoutDuration);
167
168    Future<T> future = executor.submit(callable);
169
170    try {
171      return getUninterruptibly(future, timeoutDuration, timeoutUnit);
172    } catch (TimeoutException e) {
173      future.cancel(true /* mayInterruptIfRunning */);
174      throw e;
175    } catch (ExecutionException e) {
176      wrapAndThrowExecutionExceptionOrError(e.getCause());
177      throw new AssertionError();
178    }
179  }
180
181  @Override
182  public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
183      throws TimeoutException, InterruptedException {
184    checkNotNull(runnable);
185    checkNotNull(timeoutUnit);
186    checkPositiveTimeout(timeoutDuration);
187
188    Future<?> future = executor.submit(runnable);
189
190    try {
191      future.get(timeoutDuration, timeoutUnit);
192    } catch (InterruptedException | TimeoutException e) {
193      future.cancel(true /* mayInterruptIfRunning */);
194      throw e;
195    } catch (ExecutionException e) {
196      wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
197      throw new AssertionError();
198    }
199  }
200
201  @Override
202  public void runUninterruptiblyWithTimeout(
203      Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException {
204    checkNotNull(runnable);
205    checkNotNull(timeoutUnit);
206    checkPositiveTimeout(timeoutDuration);
207
208    Future<?> future = executor.submit(runnable);
209
210    try {
211      getUninterruptibly(future, timeoutDuration, timeoutUnit);
212    } catch (TimeoutException e) {
213      future.cancel(true /* mayInterruptIfRunning */);
214      throw e;
215    } catch (ExecutionException e) {
216      wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
217      throw new AssertionError();
218    }
219  }
220
221  private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
222    Throwable cause = e.getCause();
223    if (cause == null) {
224      throw e;
225    }
226    if (combineStackTraces) {
227      StackTraceElement[] combined =
228          ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
229      cause.setStackTrace(combined);
230    }
231    if (cause instanceof Exception) {
232      throw (Exception) cause;
233    }
234    if (cause instanceof Error) {
235      throw (Error) cause;
236    }
237    // The cause is a weird kind of Throwable, so throw the outer exception.
238    throw e;
239  }
240
241  private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
242    Set<Method> set = Sets.newHashSet();
243    for (Method m : interfaceType.getMethods()) {
244      if (declaresInterruptedEx(m)) {
245        set.add(m);
246      }
247    }
248    return set;
249  }
250
251  private static boolean declaresInterruptedEx(Method method) {
252    for (Class<?> exType : method.getExceptionTypes()) {
253      // debate: == or isAssignableFrom?
254      if (exType == InterruptedException.class) {
255        return true;
256      }
257    }
258    return false;
259  }
260
261  private void wrapAndThrowExecutionExceptionOrError(Throwable cause) throws ExecutionException {
262    if (cause instanceof Error) {
263      throw new ExecutionError((Error) cause);
264    } else if (cause instanceof RuntimeException) {
265      throw new UncheckedExecutionException(cause);
266    } else {
267      throw new ExecutionException(cause);
268    }
269  }
270
271  private void wrapAndThrowRuntimeExecutionExceptionOrError(Throwable cause) {
272    if (cause instanceof Error) {
273      throw new ExecutionError((Error) cause);
274    } else {
275      throw new UncheckedExecutionException(cause);
276    }
277  }
278
279  private static void checkPositiveTimeout(long timeoutDuration) {
280    checkArgument(timeoutDuration > 0, "timeout must be positive: %s", timeoutDuration);
281  }
282}