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