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 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      public <T> T newProxy(final T target, Class<T> interfaceType,
084          final long timeoutDuration, final TimeUnit timeoutUnit) {
085        checkNotNull(target);
086        checkNotNull(interfaceType);
087        checkNotNull(timeoutUnit);
088        checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
089        checkArgument(interfaceType.isInterface(),
090            "interfaceType must be an interface type");
091    
092        final Set<Method> interruptibleMethods
093            = findInterruptibleMethods(interfaceType);
094    
095        InvocationHandler handler = new InvocationHandler() {
096          public Object invoke(Object obj, final Method method, final Object[] args)
097              throws Throwable {
098            Callable<Object> callable = new Callable<Object>() {
099              public Object call() throws Exception {
100                try {
101                  return method.invoke(target, args);
102                } catch (InvocationTargetException e) {
103                  Throwables.throwCause(e, false);
104                  throw new AssertionError("can't get here");
105                }
106              }
107            };
108            return callWithTimeout(callable, timeoutDuration, timeoutUnit,
109                interruptibleMethods.contains(method));
110          }
111        };
112        return newProxy(interfaceType, handler);
113      }
114    
115      // TODO: should this actually throw only ExecutionException?
116      public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
117          TimeUnit timeoutUnit, boolean amInterruptible) throws Exception {
118        checkNotNull(callable);
119        checkNotNull(timeoutUnit);
120        checkArgument(timeoutDuration > 0, "timeout must be positive: %s",
121            timeoutDuration);
122        Future<T> future = executor.submit(callable);
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            Future<T> uninterruptible = Futures.makeUninterruptible(future);
133            return uninterruptible.get(timeoutDuration, timeoutUnit);
134          }
135        } catch (ExecutionException e) {
136          throw Throwables.throwCause(e, true);
137        } catch (TimeoutException e) {
138          future.cancel(true);
139          throw new UncheckedTimeoutException(e);
140        }
141      }
142    
143      private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
144        Set<Method> set = Sets.newHashSet();
145        for (Method m : interfaceType.getMethods()) {
146          if (declaresInterruptedEx(m)) {
147            set.add(m);
148          }
149        }
150        return set;
151      }
152    
153      private static boolean declaresInterruptedEx(Method method) {
154        for (Class<?> exType : method.getExceptionTypes()) {
155          // debate: == or isAssignableFrom?
156          if (exType == InterruptedException.class) {
157            return true;
158          }
159        }
160        return false;
161      }
162    
163      // TODO: replace with version in common.reflect if and when it's open-sourced
164      private static <T> T newProxy(
165          Class<T> interfaceType, InvocationHandler handler) {
166        Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(),
167            new Class<?>[] { interfaceType }, handler);
168        return interfaceType.cast(object);
169      }
170    }