javadoc.src-html.com.google.common.util.concurrent.SimpleTimeLimiter.html Maven / Gradle / Ivy
The newest version!
001 /*
002 * Copyright (C) 2006 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.util.concurrent;
018
019 import static com.google.common.base.Preconditions.checkArgument;
020 import static com.google.common.base.Preconditions.checkNotNull;
021
022 import com.google.common.annotations.Beta;
023 import com.google.common.collect.ObjectArrays;
024 import com.google.common.collect.Sets;
025
026 import java.lang.reflect.InvocationHandler;
027 import java.lang.reflect.InvocationTargetException;
028 import java.lang.reflect.Method;
029 import java.lang.reflect.Proxy;
030 import java.util.Set;
031 import java.util.concurrent.Callable;
032 import java.util.concurrent.ExecutionException;
033 import java.util.concurrent.ExecutorService;
034 import java.util.concurrent.Executors;
035 import java.util.concurrent.Future;
036 import java.util.concurrent.TimeUnit;
037 import java.util.concurrent.TimeoutException;
038
039 /**
040 * A TimeLimiter that runs method calls in the background using an
041 * {@link ExecutorService}. If the time limit expires for a given method call,
042 * the thread running the call will be interrupted.
043 *
044 * @author Kevin Bourrillion
045 * @since 1.0
046 */
047 @Beta
048 public final class SimpleTimeLimiter implements TimeLimiter {
049
050 private final ExecutorService executor;
051
052 /**
053 * Constructs a TimeLimiter instance using the given executor service to
054 * execute proxied method calls.
055 * <p>
056 * <b>Warning:</b> using a bounded executor
057 * may be counterproductive! If the thread pool fills up, any time callers
058 * spend waiting for a thread may count toward their time limit, and in
059 * this case the call may even time out before the target method is ever
060 * invoked.
061 *
062 * @param executor the ExecutorService that will execute the method calls on
063 * the target objects; for example, a {@link
064 * Executors#newCachedThreadPool()}.
065 */
066 public SimpleTimeLimiter(ExecutorService executor) {
067 this.executor = checkNotNull(executor);
068 }
069
070 /**
071 * Constructs a TimeLimiter instance using a {@link
072 * Executors#newCachedThreadPool()} to execute proxied method calls.
073 *
074 * <p><b>Warning:</b> using a bounded executor may be counterproductive! If
075 * the thread pool fills up, any time callers spend waiting for a thread may
076 * count toward their time limit, and in this case the call may even time out
077 * before the target method is ever invoked.
078 */
079 public SimpleTimeLimiter() {
080 this(Executors.newCachedThreadPool());
081 }
082
083 @Override
084 public <T> T newProxy(final T target, Class<T> interfaceType,
085 final long timeoutDuration, final TimeUnit timeoutUnit) {
086 checkNotNull(target);
087 checkNotNull(interfaceType);
088 checkNotNull(timeoutUnit);
089 checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
090 checkArgument(interfaceType.isInterface(),
091 "interfaceType must be an interface type");
092
093 final Set<Method> interruptibleMethods
094 = findInterruptibleMethods(interfaceType);
095
096 InvocationHandler handler = new InvocationHandler() {
097 @Override
098 public Object invoke(Object obj, final Method method, final Object[] args)
099 throws Throwable {
100 Callable<Object> callable = new Callable<Object>() {
101 @Override
102 public Object call() throws Exception {
103 try {
104 return method.invoke(target, args);
105 } catch (InvocationTargetException e) {
106 throwCause(e, false);
107 throw new AssertionError("can't get here");
108 }
109 }
110 };
111 return callWithTimeout(callable, timeoutDuration, timeoutUnit,
112 interruptibleMethods.contains(method));
113 }
114 };
115 return newProxy(interfaceType, handler);
116 }
117
118 // TODO: should this actually throw only ExecutionException?
119 @Override
120 public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
121 TimeUnit timeoutUnit, boolean amInterruptible) throws Exception {
122 checkNotNull(callable);
123 checkNotNull(timeoutUnit);
124 checkArgument(timeoutDuration > 0, "timeout must be positive: %s",
125 timeoutDuration);
126 Future<T> future = executor.submit(callable);
127 try {
128 if (amInterruptible) {
129 try {
130 return future.get(timeoutDuration, timeoutUnit);
131 } catch (InterruptedException e) {
132 future.cancel(true);
133 throw e;
134 }
135 } else {
136 return Uninterruptibles.getUninterruptibly(future,
137 timeoutDuration, timeoutUnit);
138 }
139 } catch (ExecutionException e) {
140 throw throwCause(e, true);
141 } catch (TimeoutException e) {
142 future.cancel(true);
143 throw new UncheckedTimeoutException(e);
144 }
145 }
146
147 private static Exception throwCause(Exception e, boolean combineStackTraces)
148 throws Exception {
149 Throwable cause = e.getCause();
150 if (cause == null) {
151 throw e;
152 }
153 if (combineStackTraces) {
154 StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(),
155 e.getStackTrace(), StackTraceElement.class);
156 cause.setStackTrace(combined);
157 }
158 if (cause instanceof Exception) {
159 throw (Exception) cause;
160 }
161 if (cause instanceof Error) {
162 throw (Error) cause;
163 }
164 // The cause is a weird kind of Throwable, so throw the outer exception.
165 throw e;
166 }
167
168 private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
169 Set<Method> set = Sets.newHashSet();
170 for (Method m : interfaceType.getMethods()) {
171 if (declaresInterruptedEx(m)) {
172 set.add(m);
173 }
174 }
175 return set;
176 }
177
178 private static boolean declaresInterruptedEx(Method method) {
179 for (Class<?> exType : method.getExceptionTypes()) {
180 // debate: == or isAssignableFrom?
181 if (exType == InterruptedException.class) {
182 return true;
183 }
184 }
185 return false;
186 }
187
188 // TODO: replace with version in common.reflect if and when it's open-sourced
189 private static <T> T newProxy(
190 Class<T> interfaceType, InvocationHandler handler) {
191 Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(),
192 new Class<?>[] { interfaceType }, handler);
193 return interfaceType.cast(object);
194 }
195 }
© 2015 - 2025 Weber Informatics LLC | Privacy Policy