Skip to content

Commit

Permalink
Support executor qualification with @async#value
Browse files Browse the repository at this point in the history
Prior to this change, Spring's @async annotation support was tied to a
single AsyncTaskExecutor bean, meaning that all methods marked with
@async were forced to use the same executor. This is an undesirable
limitation, given that certain methods may have different priorities,
etc. This leads to the need to (optionally) qualify which executor
should handle each method.

This is similar to the way that Spring's @transactional annotation was
originally tied to a single PlatformTransactionManager, but in Spring
3.0 was enhanced to allow for a qualifier via the #value attribute, e.g.

  @transactional("ptm1")
  public void m() { ... }

where "ptm1" is either the name of a PlatformTransactionManager bean or
a qualifier value associated with a PlatformTransactionManager bean,
e.g. via the <qualifier> element in XML or the @qualifier annotation.

This commit introduces the same approach to @async and its relationship
to underlying executor beans. As always, the following syntax remains
supported

  @async
  public void m() { ... }

indicating that calls to #m will be delegated to the "default" executor,
i.e. the executor provided to

  <task:annotation-driven executor="..."/>

or the executor specified when authoring a @configuration class that
implements AsyncConfigurer and its #getAsyncExecutor method.

However, it now also possible to qualify which executor should be used
on a method-by-method basis, e.g.

  @async("e1")
  public void m() { ... }

indicating that calls to #m will be delegated to the executor bean
named or otherwise qualified as "e1". Unlike the default executor
which is specified up front at configuration time as described above,
the "e1" executor bean is looked up within the container on the first
execution of #m and then cached in association with that method for the
lifetime of the container.

Class-level use of Async#value behaves as expected, indicating that all
methods within the annotated class should be executed with the named
executor. In the case of both method- and class-level annotations, any
method-level #value overrides any class level #value.

This commit introduces the following major changes:

 - Add @async#value attribute for executor qualification

 - Introduce AsyncExecutionAspectSupport as a common base class for
   both MethodInterceptor- and AspectJ-based async aspects. This base
   class provides common structure for specifying the default executor
   (#setExecutor) as well as logic for determining (and caching) which
   executor should execute a given method (#determineAsyncExecutor) and
   an abstract method to allow subclasses to provide specific strategies
   for executor qualification (#getExecutorQualifier).

 - Introduce AnnotationAsyncExecutionInterceptor as a specialization of
   the existing AsyncExecutionInterceptor to allow for introspection of
   the @async annotation and its #value attribute for a given method.
   Note that this new subclass was necessary for packaging reasons -
   the original AsyncExecutionInterceptor lives in
   org.springframework.aop and therefore does not have visibility to
   the @async annotation in org.springframework.scheduling.annotation.
   This new subclass replaces usage of AsyncExecutionInterceptor
   throughout the framework, though the latter remains usable and
   undeprecated for compatibility with any existing third-party
   extensions.

 - Add documentation to spring-task-3.2.xsd and reference manual
   explaining @async executor qualification

 - Add tests covering all new functionality

Note that the public API of all affected components remains backward-
compatible.

Issue: SPR-6847
  • Loading branch information
cbeams committed May 20, 2012
1 parent 3fb1187 commit ed0576c
Show file tree
Hide file tree
Showing 15 changed files with 559 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.aop.interceptor;

import java.lang.reflect.Method;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
* Base class for asynchronous method execution aspects, such as
* {@link org.springframework.scheduling.annotation.AnnotationAsyncExecutionInterceptor}
* or {@link org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect}.
*
* <p>Provides support for <i>executor qualification</i> on a method-by-method basis.
* {@code AsyncExecutionAspectSupport} objects must be constructed with a default {@code
* Executor}, but each individual method may further qualify a specific {@code Executor}
* bean to be used when executing it, e.g. through an annotation attribute.
*
* @author Chris Beams
* @since 3.2
*/
public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware {

private final Map<Method, AsyncTaskExecutor> executors = new HashMap<Method, AsyncTaskExecutor>();

private Executor defaultExecutor;

private BeanFactory beanFactory;


/**
* Create a new {@link AsyncExecutionAspectSupport}, using the provided default
* executor unless individual async methods indicate via qualifier that a more
* specific executor should be used.
* @param defaultExecutor the executor to use when executing asynchronous methods
*/
public AsyncExecutionAspectSupport(Executor defaultExecutor) {
this.setExecutor(defaultExecutor);
}


/**
* Supply the executor to be used when executing async methods.
* @param defaultExecutor the {@code Executor} (typically a Spring {@code
* AsyncTaskExecutor} or {@link java.util.concurrent.ExecutorService}) to delegate to
* unless a more specific executor has been requested via a qualifier on the async
* method, in which case the executor will be looked up at invocation time against the
* enclosing bean factory.
* @see #getExecutorQualifier
* @see #setBeanFactory(BeanFactory)
*/
public void setExecutor(Executor defaultExecutor) {
this.defaultExecutor = defaultExecutor;
}

/**
* Set the {@link BeanFactory} to be used when looking up executors by qualifier.
*/
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}

/**
* Return the qualifier or bean name of the executor to be used when executing the
* given async method, typically specified in the form of an annotation attribute.
* Returning an empty string or {@code null} indicates that no specific executor has
* been specified and that the {@linkplain #setExecutor(Executor) default executor}
* should be used.
* @param method the method to inspect for executor qualifier metadata
* @return the qualifier if specified, otherwise empty string or {@code null}
* @see #determineAsyncExecutor(Method)
*/
protected abstract String getExecutorQualifier(Method method);

/**
* Determine the specific executor to use when executing the given method.
* @returns the executor to use (never {@code null})
*/
protected AsyncTaskExecutor determineAsyncExecutor(Method method) {
if (!this.executors.containsKey(method)) {
Executor executor = this.defaultExecutor;

String qualifier = getExecutorQualifier(method);
if (StringUtils.hasLength(qualifier)) {
Assert.notNull(this.beanFactory,
"BeanFactory must be set on " + this.getClass().getSimpleName() +
" to access qualified executor [" + qualifier + "]");
executor = BeanFactoryUtils.qualifiedBeanOfType(this.beanFactory, Executor.class, qualifier);
}

if (executor instanceof AsyncTaskExecutor) {
this.executors.put(method, (AsyncTaskExecutor) executor);
}
else if (executor instanceof Executor) {
this.executors.put(method, new TaskExecutorAdapter(executor));
}
}

return this.executors.get(method);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package org.springframework.aop.interceptor;

import java.lang.reflect.Method;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
Expand All @@ -25,8 +27,6 @@

import org.springframework.core.Ordered;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

/**
Expand All @@ -44,39 +44,39 @@
* (like Spring's {@link org.springframework.scheduling.annotation.AsyncResult}
* or EJB 3.1's <code>javax.ejb.AsyncResult</code>).
*
* <p>As of Spring 3.2 the {@code AnnotationAsyncExecutionInterceptor} subclass is
* preferred for use due to its support for executor qualification in conjunction with
* Spring's {@code @Async} annotation.
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 3.0
* @see org.springframework.scheduling.annotation.Async
* @see org.springframework.scheduling.annotation.AsyncAnnotationAdvisor
* @see org.springframework.scheduling.annotation.AnnotationAsyncExecutionInterceptor
*/
public class AsyncExecutionInterceptor implements MethodInterceptor, Ordered {

private final AsyncTaskExecutor asyncExecutor;

public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport
implements MethodInterceptor, Ordered {

/**
* Create a new {@code AsyncExecutionInterceptor}.
* @param executor the {@link Executor} (typically a Spring {@link AsyncTaskExecutor}
* or {@link java.util.concurrent.ExecutorService}) to delegate to.
*/
public AsyncExecutionInterceptor(AsyncTaskExecutor asyncExecutor) {
Assert.notNull(asyncExecutor, "TaskExecutor must not be null");
this.asyncExecutor = asyncExecutor;
public AsyncExecutionInterceptor(Executor executor) {
super(executor);
}


/**
* Create a new AsyncExecutionInterceptor.
* @param asyncExecutor the <code>java.util.concurrent</code> Executor
* to delegate to (typically a {@link java.util.concurrent.ExecutorService}
* Intercept the given method invocation, submit the actual calling of the method to
* the correct task executor and return immediately to the caller.
* @param invocation the method to intercept and make asynchronous
* @return {@link Future} if the original method returns {@code Future}; {@code null}
* otherwise.
*/
public AsyncExecutionInterceptor(Executor asyncExecutor) {
this.asyncExecutor = new TaskExecutorAdapter(asyncExecutor);
}


public Object invoke(final MethodInvocation invocation) throws Throwable {
Future<?> result = this.asyncExecutor.submit(
Future<?> result = this.determineAsyncExecutor(invocation.getMethod()).submit(
new Callable<Object>() {
public Object call() throws Exception {
try {
Expand All @@ -99,6 +99,20 @@ public Object call() throws Exception {
}
}

/**
* {@inheritDoc}
* <p>This implementation is a no-op for compatibility in Spring 3.2. Subclasses may
* override to provide support for extracting qualifier information, e.g. via an
* annotation on the given method.
* @return always {@code null}
* @see #determineAsyncExecutor(Method)
* @since 3.2
*/
@Override
protected String getExecutorQualifier(Method method) {
return null;
}

public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import java.util.concurrent.Executor;
import java.util.concurrent.Future;

import org.aspectj.lang.reflect.MethodSignature;

import org.springframework.aop.interceptor.AsyncExecutionAspectSupport;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;

/**
* Abstract aspect that routes selected methods asynchronously.
Expand All @@ -34,19 +34,18 @@ import org.springframework.core.task.support.TaskExecutorAdapter;
*
* @author Ramnivas Laddad
* @author Juergen Hoeller
* @author Chris Beams
* @since 3.0.5
*/
public abstract aspect AbstractAsyncExecutionAspect {

private AsyncTaskExecutor asyncExecutor;
public abstract aspect AbstractAsyncExecutionAspect extends AsyncExecutionAspectSupport {

public void setExecutor(Executor executor) {
if (executor instanceof AsyncTaskExecutor) {
this.asyncExecutor = (AsyncTaskExecutor) executor;
}
else {
this.asyncExecutor = new TaskExecutorAdapter(executor);
}
/**
* Create an {@code AnnotationAsyncExecutionAspect} with a {@code null} default
* executor, which should instead be set via {@code #aspectOf} and
* {@link #setExecutor(Executor)}.
*/
public AbstractAsyncExecutionAspect() {
super(null);
}

/**
Expand All @@ -57,7 +56,9 @@ public abstract aspect AbstractAsyncExecutionAspect {
* otherwise.
*/
Object around() : asyncMethod() {
if (this.asyncExecutor == null) {
MethodSignature methodSignature = (MethodSignature) thisJoinPointStaticPart.getSignature();
AsyncTaskExecutor executor = determineAsyncExecutor(methodSignature.getMethod());
if (executor == null) {
return proceed();
}
Callable<Object> callable = new Callable<Object>() {
Expand All @@ -68,8 +69,8 @@ public abstract aspect AbstractAsyncExecutionAspect {
}
return null;
}};
Future<?> result = this.asyncExecutor.submit(callable);
if (Future.class.isAssignableFrom(((MethodSignature) thisJoinPointStaticPart.getSignature()).getReturnType())) {
Future<?> result = executor.submit(callable);
if (Future.class.isAssignableFrom(methodSignature.getReturnType())) {
return result;
}
else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

package org.springframework.scheduling.aspectj;

import java.lang.reflect.Method;

import java.util.concurrent.Future;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.annotation.Async;

/**
Expand All @@ -31,6 +35,7 @@ import org.springframework.scheduling.annotation.Async;
* constraint, it produces only a warning.
*
* @author Ramnivas Laddad
* @author Chris Beams
* @since 3.0.5
*/
public aspect AnnotationAsyncExecutionAspect extends AbstractAsyncExecutionAspect {
Expand All @@ -43,6 +48,28 @@ public aspect AnnotationAsyncExecutionAspect extends AbstractAsyncExecutionAspec

public pointcut asyncMethod() : asyncMarkedMethod() || asyncTypeMarkedMethod();

/**
* {@inheritDoc}
* <p>This implementation inspects the given method and its declaring class for the
* {@code @Async} annotation, returning the qualifier value expressed by
* {@link Async#value()}. If {@code @Async} is specified at both the method and class level, the
* method's {@code #value} takes precedence (even if empty string, indicating that
* the default executor should be used preferentially).
* @return the qualifier if specified, otherwise empty string indicating that the
* {@linkplain #setExecutor(Executor) default executor} should be used
* @see #determineAsyncExecutor(Method)
*/
@Override
protected String getExecutorQualifier(Method method) {
// maintainer's note: changes made here should also be made in
// AnnotationAsyncExecutionInterceptor#getExecutorQualifier
Async async = AnnotationUtils.findAnnotation(method, Async.class);
if (async == null) {
async = AnnotationUtils.findAnnotation(method.getDeclaringClass(), Async.class);
}
return async == null ? null : async.value();
}

declare error:
execution(@Async !(void||Future) *(..)):
"Only methods that return void or Future may have an @Async annotation";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,16 @@

import org.junit.Before;
import org.junit.Test;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.startsWith;

import static org.junit.Assert.*;

Expand Down Expand Up @@ -104,6 +111,22 @@ public void methodReturningNonVoidNonFutureInAsyncClassGetsRoutedSynchronously()
assertEquals(0, executor.submitCompleteCounter);
}

@Test
public void qualifiedAsyncMethodsAreRoutedToCorrectExecutor() throws InterruptedException, ExecutionException {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("e1", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
AnnotationAsyncExecutionAspect.aspectOf().setBeanFactory(beanFactory);

ClassWithQualifiedAsyncMethods obj = new ClassWithQualifiedAsyncMethods();

Future<Thread> defaultThread = obj.defaultWork();
assertThat(defaultThread.get(), not(Thread.currentThread()));
assertThat(defaultThread.get().getName(), not(startsWith("e1-")));

Future<Thread> e1Thread = obj.e1Work();
assertThat(e1Thread.get().getName(), startsWith("e1-"));
}


@SuppressWarnings("serial")
private static class CountingExecutor extends SimpleAsyncTaskExecutor {
Expand Down Expand Up @@ -180,4 +203,16 @@ public Future<Integer> incrementReturningAFuture() {
}
}


static class ClassWithQualifiedAsyncMethods {
@Async
public Future<Thread> defaultWork() {
return new AsyncResult<Thread>(Thread.currentThread());
}

@Async("e1")
public Future<Thread> e1Work() {
return new AsyncResult<Thread>(Thread.currentThread());
}
}
}
Loading

0 comments on commit ed0576c

Please sign in to comment.