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.Beta; 021import com.google.common.annotations.GwtIncompatible; 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@Beta 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 private <T extends @Nullable Object> T callWithTimeout( 115 Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible) 116 throws Exception { 117 checkNotNull(callable); 118 checkNotNull(timeoutUnit); 119 checkPositiveTimeout(timeoutDuration); 120 121 Future<T> future = executor.submit(callable); 122 123 try { 124 if (amInterruptible) { 125 try { 126 return future.get(timeoutDuration, timeoutUnit); 127 } catch (InterruptedException e) { 128 future.cancel(true); 129 throw e; 130 } 131 } else { 132 return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit); 133 } 134 } catch (ExecutionException e) { 135 throw throwCause(e, true /* combineStackTraces */); 136 } catch (TimeoutException e) { 137 future.cancel(true); 138 throw new UncheckedTimeoutException(e); 139 } 140 } 141 142 @CanIgnoreReturnValue 143 @Override 144 public <T extends @Nullable Object> T callWithTimeout( 145 Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit) 146 throws TimeoutException, InterruptedException, ExecutionException { 147 checkNotNull(callable); 148 checkNotNull(timeoutUnit); 149 checkPositiveTimeout(timeoutDuration); 150 151 Future<T> future = executor.submit(callable); 152 153 try { 154 return future.get(timeoutDuration, timeoutUnit); 155 } catch (InterruptedException | TimeoutException e) { 156 future.cancel(true /* mayInterruptIfRunning */); 157 throw e; 158 } catch (ExecutionException e) { 159 wrapAndThrowExecutionExceptionOrError(e.getCause()); 160 throw new AssertionError(); 161 } 162 } 163 164 @CanIgnoreReturnValue 165 @Override 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 Uninterruptibles.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 Uninterruptibles.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}