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