001 /*
002 * Copyright (C) 2006 Google Inc.
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.base.Throwables;
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
046 */
047 @Beta
048 public 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 * java.util.concurrent.Executors#newCachedThreadPool()}.
065 */
066 public SimpleTimeLimiter(ExecutorService executor) {
067 checkNotNull(executor);
068 this.executor = executor;
069 }
070
071 /**
072 * Constructs a TimeLimiter instance using a {@link
073 * java.util.concurrent.Executors#newCachedThreadPool()} to execute proxied
074 * method calls.
075 *
076 * <p><b>Warning:</b> using a bounded executor may be counterproductive! If
077 * the thread pool fills up, any time callers spend waiting for a thread may
078 * count toward their time limit, and in this case the call may even time out
079 * before the target method is ever invoked.
080 */
081 public SimpleTimeLimiter() {
082 this(Executors.newCachedThreadPool());
083 }
084
085 public <T> T newProxy(final T target, Class<T> interfaceType,
086 final long timeoutDuration, final TimeUnit timeoutUnit) {
087 checkNotNull(target);
088 checkNotNull(interfaceType);
089 checkNotNull(timeoutUnit);
090 checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
091 checkArgument(interfaceType.isInterface(),
092 "interfaceType must be an interface type");
093
094 final Set<Method> interruptibleMethods
095 = findInterruptibleMethods(interfaceType);
096
097 InvocationHandler handler = new InvocationHandler() {
098 public Object invoke(Object obj, final Method method, final Object[] args)
099 throws Throwable {
100 Callable<Object> callable = new Callable<Object>() {
101 public Object call() throws Exception {
102 try {
103 return method.invoke(target, args);
104 } catch (InvocationTargetException e) {
105 Throwables.throwCause(e, false);
106 throw new AssertionError("can't get here");
107 }
108 }
109 };
110 return callWithTimeout(callable, timeoutDuration, timeoutUnit,
111 interruptibleMethods.contains(method));
112 }
113 };
114 return newProxy(interfaceType, handler);
115 }
116
117 // TODO: should this actually throw only ExecutionException?
118 public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
119 TimeUnit timeoutUnit, boolean amInterruptible) throws Exception {
120 checkNotNull(callable);
121 checkNotNull(timeoutUnit);
122 checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
123 Future<T> future = executor.submit(callable);
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 Future<T> uninterruptible = Futures.makeUninterruptible(future);
134 return uninterruptible.get(timeoutDuration, timeoutUnit);
135 }
136 } catch (ExecutionException e) {
137 throw Throwables.throwCause(e, true);
138 } catch (TimeoutException e) {
139 future.cancel(true);
140 throw new UncheckedTimeoutException(e);
141 }
142 }
143
144 private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
145 Set<Method> set = Sets.newHashSet();
146 for (Method m : interfaceType.getMethods()) {
147 if (declaresInterruptedEx(m)) {
148 set.add(m);
149 }
150 }
151 return set;
152 }
153
154 private static boolean declaresInterruptedEx(Method method) {
155 for (Class<?> exType : method.getExceptionTypes()) {
156 // debate: == or isAssignableFrom?
157 if (exType == InterruptedException.class) {
158 return true;
159 }
160 }
161 return false;
162 }
163
164 // TODO: replace with version in common.reflect if and when it's open-sourced
165 private static <T> T newProxy(
166 Class<T> interfaceType, InvocationHandler handler) {
167 Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(),
168 new Class<?>[] { interfaceType }, handler);
169 return interfaceType.cast(object);
170 }
171 }