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; 037 038/** 039 * A TimeLimiter that runs method calls in the background using an {@link ExecutorService}. If the 040 * time limit expires for a given method call, the thread running the call will be interrupted. 041 * 042 * @author Kevin Bourrillion 043 * @author Jens Nyman 044 * @since 1.0 045 */ 046@Beta 047@GwtIncompatible 048public final class SimpleTimeLimiter implements TimeLimiter { 049 050 private final ExecutorService executor; 051 052 private 053 SimpleTimeLimiter(ExecutorService executor) { 054 this.executor = checkNotNull(executor); 055 } 056 057 /** 058 * Creates a TimeLimiter instance using the given executor service to execute method calls. 059 * 060 * <p><b>Warning:</b> using a bounded executor may be counterproductive! If the thread pool fills 061 * up, any time callers spend waiting for a thread may count toward their time limit, and in this 062 * case the call may even time out before the target method is ever invoked. 063 * 064 * @param executor the ExecutorService that will execute the method calls on the target objects; 065 * for example, a {@link Executors#newCachedThreadPool()}. 066 * @since 22.0 067 */ 068 public static SimpleTimeLimiter create(ExecutorService executor) { 069 return new SimpleTimeLimiter(executor); 070 } 071 072 @Override 073 public <T> T newProxy( 074 final T target, 075 Class<T> interfaceType, 076 final long timeoutDuration, 077 final 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 final Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType); 085 086 InvocationHandler handler = 087 new InvocationHandler() { 088 @Override 089 public Object invoke(Object obj, final Method method, final Object[] args) 090 throws Throwable { 091 Callable<Object> callable = 092 new Callable<Object>() { 093 @Override 094 public Object call() throws Exception { 095 try { 096 return method.invoke(target, args); 097 } catch (InvocationTargetException e) { 098 throw throwCause(e, false /* combineStackTraces */); 099 } 100 } 101 }; 102 return callWithTimeout( 103 callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method)); 104 } 105 }; 106 return newProxy(interfaceType, handler); 107 } 108 109 private 110 <T> T callWithTimeout( 111 Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible) 112 throws Exception { 113 checkNotNull(callable); 114 checkNotNull(timeoutUnit); 115 checkPositiveTimeout(timeoutDuration); 116 117 Future<T> future = executor.submit(callable); 118 119 try { 120 if (amInterruptible) { 121 try { 122 return future.get(timeoutDuration, timeoutUnit); 123 } catch (InterruptedException e) { 124 future.cancel(true); 125 throw e; 126 } 127 } else { 128 return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit); 129 } 130 } catch (ExecutionException e) { 131 throw throwCause(e, true /* combineStackTraces */); 132 } catch (TimeoutException e) { 133 future.cancel(true); 134 throw new UncheckedTimeoutException(e); 135 } 136 } 137 138 @CanIgnoreReturnValue 139 @Override 140 public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit) 141 throws TimeoutException, InterruptedException, ExecutionException { 142 checkNotNull(callable); 143 checkNotNull(timeoutUnit); 144 checkPositiveTimeout(timeoutDuration); 145 146 Future<T> future = executor.submit(callable); 147 148 try { 149 return future.get(timeoutDuration, timeoutUnit); 150 } catch (InterruptedException | TimeoutException e) { 151 future.cancel(true /* mayInterruptIfRunning */); 152 throw e; 153 } catch (ExecutionException e) { 154 wrapAndThrowExecutionExceptionOrError(e.getCause()); 155 throw new AssertionError(); 156 } 157 } 158 159 @CanIgnoreReturnValue 160 @Override 161 public <T> 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 Uninterruptibles.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 Uninterruptibles.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 // TODO: replace with version in common.reflect if and when it's open-sourced 262 private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) { 263 Object object = 264 Proxy.newProxyInstance( 265 interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, handler); 266 return interfaceType.cast(object); 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}