@Target(value=METHOD) @Retention(value=RUNTIME) public @interface Async
Future or no value (void or Void). To enable asynchronous
method support, use GuiceAsync.enableFor(com.google.inject.Binder) in
any of your modules.
Method calls are intercepted and the call is then executed in a different
thread using an ExecutorService. The ExecutorService instance that
will be used is looked up using the Injector.
Key that is used to retrieve the actual ExecutorService.
BindingAnnotation including Named on the
method to specify the annotation part of the Key.Executor to specify the class part of the Key.
@Async
@Named("computationExecutor")
@Executor(AdvancedExecutorService.class)
public void compute() {...}
In this case, the Executor to use will be looked up like
injector.getInstance(Key.get(AdvancedExecutorService.class,
Names.named("computationExecutor"))
If you leave out the Executor part, the class defaults to
ExecutorService.class. If you leave out the binding annotation, the
created key will not have an annotation part. If you put neither a binding
annotation nor an Executor class on the method, a default ExecutorService is
used that is created internally. You should make no assumptions about the
actual behavior of that service and it is highly recommended to bind and
specify an ExecutorService yourself.
public class MyModule extends AbstractModule {
@Provides
public ThreadFactory provideMyThreadFactory() {
return new ThreadFactoryBuilder()....build(); // class from Google guava
}
@Provides
@Named("mainThreadPool")
public ExecutorService provideMyExecutor(ThreadFactory threadFactory) {
return Executors.newFixedThreadPool(4, threadFactory);
}
}
Future object. To implement such a method, you can
obtain a Future for an arbitrary value using Futures.delegate(Object)
like in:
@Async
public Future<Double> compute() {
final double result = realComputation();
return Futures.delegate(result);
}
The dummy Future object created here will be replaced with a real Future
object that is obtained from the ExecutorService.
ExecutionException which will be thrown by Future.get().
This annotation is subject to all limitations that apply to
MethodInterceptors. Please see the guice wiki for
more information.
Copyright © 2014–2016. All rights reserved.