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.checkerframework.checker.nullness.qual.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        new InvocationHandler() {
088          @Override
089          public @Nullable Object invoke(
090              Object obj, Method method, @Nullable Object @Nullable [] args) throws Throwable {
091            Callable<@Nullable Object> callable =
092                () -> {
093                  try {
094                    return method.invoke(target, args);
095                  } catch (InvocationTargetException e) {
096                    throw throwCause(e, false /* combineStackTraces */);
097                  }
098                };
099            return callWithTimeout(
100                callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method));
101          }
102        };
103    return newProxy(interfaceType, handler);
104  }
105
106  // TODO: replace with version in common.reflect if and when it's open-sourced
107  private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
108    Object object =
109        Proxy.newProxyInstance(
110            interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, handler);
111    return interfaceType.cast(object);
112  }
113
114  @ParametricNullness
115  private <T extends @Nullable Object> T callWithTimeout(
116      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
117      throws Exception {
118    checkNotNull(callable);
119    checkNotNull(timeoutUnit);
120    checkPositiveTimeout(timeoutDuration);
121
122    Future<T> future = executor.submit(callable);
123
124    try {
125      return amInterruptible
126          ? future.get(timeoutDuration, timeoutUnit)
127          : getUninterruptibly(future, timeoutDuration, timeoutUnit);
128    } catch (InterruptedException e) {
129      future.cancel(true);
130      throw e;
131    } catch (ExecutionException e) {
132      throw throwCause(e, true /* combineStackTraces */);
133    } catch (TimeoutException e) {
134      future.cancel(true);
135      throw new UncheckedTimeoutException(e);
136    }
137  }
138
139  @CanIgnoreReturnValue
140  @Override
141  @ParametricNullness
142  public <T extends @Nullable Object> T callWithTimeout(
143      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
144      throws TimeoutException, InterruptedException, ExecutionException {
145    checkNotNull(callable);
146    checkNotNull(timeoutUnit);
147    checkPositiveTimeout(timeoutDuration);
148
149    Future<T> future = executor.submit(callable);
150
151    try {
152      return future.get(timeoutDuration, timeoutUnit);
153    } catch (InterruptedException | TimeoutException e) {
154      future.cancel(true /* mayInterruptIfRunning */);
155      throw e;
156    } catch (ExecutionException e) {
157      wrapAndThrowExecutionExceptionOrError(e.getCause());
158      throw new AssertionError();
159    }
160  }
161
162  @CanIgnoreReturnValue
163  @Override
164  @ParametricNullness
165  public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
166      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
167      throws TimeoutException, ExecutionException {
168    checkNotNull(callable);
169    checkNotNull(timeoutUnit);
170    checkPositiveTimeout(timeoutDuration);
171
172    Future<T> future = executor.submit(callable);
173
174    try {
175      return getUninterruptibly(future, timeoutDuration, timeoutUnit);
176    } catch (TimeoutException e) {
177      future.cancel(true /* mayInterruptIfRunning */);
178      throw e;
179    } catch (ExecutionException e) {
180      wrapAndThrowExecutionExceptionOrError(e.getCause());
181      throw new AssertionError();
182    }
183  }
184
185  @Override
186  public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
187      throws TimeoutException, InterruptedException {
188    checkNotNull(runnable);
189    checkNotNull(timeoutUnit);
190    checkPositiveTimeout(timeoutDuration);
191
192    Future<?> future = executor.submit(runnable);
193
194    try {
195      future.get(timeoutDuration, timeoutUnit);
196    } catch (InterruptedException | TimeoutException e) {
197      future.cancel(true /* mayInterruptIfRunning */);
198      throw e;
199    } catch (ExecutionException e) {
200      wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
201      throw new AssertionError();
202    }
203  }
204
205  @Override
206  public void runUninterruptiblyWithTimeout(
207      Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException {
208    checkNotNull(runnable);
209    checkNotNull(timeoutUnit);
210    checkPositiveTimeout(timeoutDuration);
211
212    Future<?> future = executor.submit(runnable);
213
214    try {
215      getUninterruptibly(future, timeoutDuration, timeoutUnit);
216    } catch (TimeoutException e) {
217      future.cancel(true /* mayInterruptIfRunning */);
218      throw e;
219    } catch (ExecutionException e) {
220      wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
221      throw new AssertionError();
222    }
223  }
224
225  private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
226    Throwable cause = e.getCause();
227    if (cause == null) {
228      throw e;
229    }
230    if (combineStackTraces) {
231      StackTraceElement[] combined =
232          ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
233      cause.setStackTrace(combined);
234    }
235    if (cause instanceof Exception) {
236      throw (Exception) cause;
237    }
238    if (cause instanceof Error) {
239      throw (Error) cause;
240    }
241    // The cause is a weird kind of Throwable, so throw the outer exception.
242    throw e;
243  }
244
245  private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
246    Set<Method> set = Sets.newHashSet();
247    for (Method m : interfaceType.getMethods()) {
248      if (declaresInterruptedEx(m)) {
249        set.add(m);
250      }
251    }
252    return set;
253  }
254
255  private static boolean declaresInterruptedEx(Method method) {
256    for (Class<?> exType : method.getExceptionTypes()) {
257      // debate: == or isAssignableFrom?
258      if (exType == InterruptedException.class) {
259        return true;
260      }
261    }
262    return false;
263  }
264
265  private void wrapAndThrowExecutionExceptionOrError(Throwable cause) throws ExecutionException {
266    if (cause instanceof Error) {
267      throw new ExecutionError((Error) cause);
268    } else if (cause instanceof RuntimeException) {
269      throw new UncheckedExecutionException(cause);
270    } else {
271      throw new ExecutionException(cause);
272    }
273  }
274
275  private void wrapAndThrowRuntimeExecutionExceptionOrError(Throwable cause) {
276    if (cause instanceof Error) {
277      throw new ExecutionError((Error) cause);
278    } else {
279      throw new UncheckedExecutionException(cause);
280    }
281  }
282
283  private static void checkPositiveTimeout(long timeoutDuration) {
284    checkArgument(timeoutDuration > 0, "timeout must be positive: %s", timeoutDuration);
285  }
286}