Search in sources :

Example 1 with AsyncTaskExecutor

use of org.springframework.core.task.AsyncTaskExecutor in project spring-framework by spring-projects.

the class AsyncExecutionInterceptor method invoke.

/**
	 * 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.
	 */
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
    final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
    AsyncTaskExecutor executor = determineAsyncExecutor(userDeclaredMethod);
    if (executor == null) {
        throw new IllegalStateException("No executor specified and no default executor set on AsyncExecutionInterceptor either");
    }
    Callable<Object> task = new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            try {
                Object result = invocation.proceed();
                if (result instanceof Future) {
                    return ((Future<?>) result).get();
                }
            } catch (ExecutionException ex) {
                handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
            } catch (Throwable ex) {
                handleError(ex, userDeclaredMethod, invocation.getArguments());
            }
            return null;
        }
    };
    return doSubmit(task, executor, invocation.getMethod().getReturnType());
}
Also used : Future(java.util.concurrent.Future) Method(java.lang.reflect.Method) AsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) ExecutionException(java.util.concurrent.ExecutionException) Callable(java.util.concurrent.Callable)

Example 2 with AsyncTaskExecutor

use of org.springframework.core.task.AsyncTaskExecutor in project spring-framework by spring-projects.

the class WebAsyncManagerTimeoutTests method setup.

@Before
public void setup() {
    this.servletRequest = new MockHttpServletRequest("GET", "/test");
    this.servletRequest.setAsyncSupported(true);
    this.servletResponse = new MockHttpServletResponse();
    this.asyncWebRequest = new StandardServletAsyncWebRequest(servletRequest, servletResponse);
    AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
    this.asyncManager = WebAsyncUtils.getAsyncManager(servletRequest);
    this.asyncManager.setTaskExecutor(executor);
    this.asyncManager.setAsyncWebRequest(this.asyncWebRequest);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) AsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) Before(org.junit.Before)

Example 3 with AsyncTaskExecutor

use of org.springframework.core.task.AsyncTaskExecutor in project spring-framework by spring-projects.

the class WebAsyncManagerTests method startCallableProcessingWithAsyncTask.

@Test
public void startCallableProcessingWithAsyncTask() throws Exception {
    AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
    given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest);
    @SuppressWarnings("unchecked") WebAsyncTask<Object> asyncTask = new WebAsyncTask<>(1000L, executor, mock(Callable.class));
    this.asyncManager.startCallableProcessing(asyncTask);
    verify(executor).submit((Runnable) notNull());
    verify(this.asyncWebRequest).setTimeout(1000L);
    verify(this.asyncWebRequest).addTimeoutHandler(any(Runnable.class));
    verify(this.asyncWebRequest).addCompletionHandler(any(Runnable.class));
    verify(this.asyncWebRequest).startAsync();
}
Also used : AsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) Callable(java.util.concurrent.Callable) Test(org.junit.Test)

Example 4 with AsyncTaskExecutor

use of org.springframework.core.task.AsyncTaskExecutor in project spring-framework by spring-projects.

the class AsyncExecutionAspectSupport method determineAsyncExecutor.

/**
	 * Determine the specific executor to use when executing the given method.
	 * Should preferably return an {@link AsyncListenableTaskExecutor} implementation.
	 * @return the executor to use (or {@code null}, but just if no default executor is available)
	 */
protected AsyncTaskExecutor determineAsyncExecutor(Method method) {
    AsyncTaskExecutor executor = this.executors.get(method);
    if (executor == null) {
        Executor targetExecutor;
        String qualifier = getExecutorQualifier(method);
        if (StringUtils.hasLength(qualifier)) {
            targetExecutor = findQualifiedExecutor(this.beanFactory, qualifier);
        } else {
            targetExecutor = this.defaultExecutor;
            if (targetExecutor == null) {
                synchronized (this.executors) {
                    if (this.defaultExecutor == null) {
                        this.defaultExecutor = getDefaultExecutor(this.beanFactory);
                    }
                    targetExecutor = this.defaultExecutor;
                }
            }
        }
        if (targetExecutor == null) {
            return null;
        }
        executor = (targetExecutor instanceof AsyncListenableTaskExecutor ? (AsyncListenableTaskExecutor) targetExecutor : new TaskExecutorAdapter(targetExecutor));
        this.executors.put(method, executor);
    }
    return executor;
}
Also used : AsyncListenableTaskExecutor(org.springframework.core.task.AsyncListenableTaskExecutor) Executor(java.util.concurrent.Executor) AsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor) AsyncListenableTaskExecutor(org.springframework.core.task.AsyncListenableTaskExecutor) TaskExecutor(org.springframework.core.task.TaskExecutor) AsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor) TaskExecutorAdapter(org.springframework.core.task.support.TaskExecutorAdapter)

Example 5 with AsyncTaskExecutor

use of org.springframework.core.task.AsyncTaskExecutor in project spring-framework by spring-projects.

the class SimpleTaskWorkManager method executeWork.

/**
	 * Execute the given Work on the specified TaskExecutor.
	 * @param taskExecutor the TaskExecutor to use
	 * @param work the Work to execute
	 * @param startTimeout the time duration within which the Work is supposed to start
	 * @param blockUntilStarted whether to block until the Work has started
	 * @param executionContext the JCA ExecutionContext for the given Work
	 * @param workListener the WorkListener to clal for the given Work
	 * @return the time elapsed from Work acceptance until start of execution
	 * (or -1 if not applicable or not known)
	 * @throws WorkException if the TaskExecutor did not accept the Work
	 */
protected long executeWork(TaskExecutor taskExecutor, Work work, long startTimeout, boolean blockUntilStarted, ExecutionContext executionContext, WorkListener workListener) throws WorkException {
    if (executionContext != null && executionContext.getXid() != null) {
        throw new WorkException("SimpleTaskWorkManager does not supported imported XIDs: " + executionContext.getXid());
    }
    WorkListener workListenerToUse = workListener;
    if (workListenerToUse == null) {
        workListenerToUse = new WorkAdapter();
    }
    boolean isAsync = (taskExecutor instanceof AsyncTaskExecutor);
    DelegatingWorkAdapter workHandle = new DelegatingWorkAdapter(work, workListenerToUse, !isAsync);
    try {
        if (isAsync) {
            ((AsyncTaskExecutor) taskExecutor).execute(workHandle, startTimeout);
        } else {
            taskExecutor.execute(workHandle);
        }
    } catch (TaskTimeoutException ex) {
        WorkException wex = new WorkRejectedException("TaskExecutor rejected Work because of timeout: " + work, ex);
        wex.setErrorCode(WorkException.START_TIMED_OUT);
        workListenerToUse.workRejected(new WorkEvent(this, WorkEvent.WORK_REJECTED, work, wex));
        throw wex;
    } catch (TaskRejectedException ex) {
        WorkException wex = new WorkRejectedException("TaskExecutor rejected Work: " + work, ex);
        wex.setErrorCode(WorkException.INTERNAL);
        workListenerToUse.workRejected(new WorkEvent(this, WorkEvent.WORK_REJECTED, work, wex));
        throw wex;
    } catch (Throwable ex) {
        WorkException wex = new WorkException("TaskExecutor failed to execute Work: " + work, ex);
        wex.setErrorCode(WorkException.INTERNAL);
        throw wex;
    }
    if (isAsync) {
        workListenerToUse.workAccepted(new WorkEvent(this, WorkEvent.WORK_ACCEPTED, work, null));
    }
    if (blockUntilStarted) {
        long acceptanceTime = System.currentTimeMillis();
        synchronized (workHandle.monitor) {
            try {
                while (!workHandle.started) {
                    workHandle.monitor.wait();
                }
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
        return (System.currentTimeMillis() - acceptanceTime);
    } else {
        return WorkManager.UNKNOWN;
    }
}
Also used : TaskRejectedException(org.springframework.core.task.TaskRejectedException) WorkException(javax.resource.spi.work.WorkException) WorkRejectedException(javax.resource.spi.work.WorkRejectedException) WorkListener(javax.resource.spi.work.WorkListener) AsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) WorkEvent(javax.resource.spi.work.WorkEvent) TaskTimeoutException(org.springframework.core.task.TaskTimeoutException) WorkAdapter(javax.resource.spi.work.WorkAdapter)

Aggregations

AsyncTaskExecutor (org.springframework.core.task.AsyncTaskExecutor)6 SimpleAsyncTaskExecutor (org.springframework.core.task.SimpleAsyncTaskExecutor)4 Callable (java.util.concurrent.Callable)2 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1 Executor (java.util.concurrent.Executor)1 Future (java.util.concurrent.Future)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 WorkAdapter (javax.resource.spi.work.WorkAdapter)1 WorkEvent (javax.resource.spi.work.WorkEvent)1 WorkException (javax.resource.spi.work.WorkException)1 WorkListener (javax.resource.spi.work.WorkListener)1 WorkRejectedException (javax.resource.spi.work.WorkRejectedException)1 Before (org.junit.Before)1 Test (org.junit.Test)1 AsyncListenableTaskExecutor (org.springframework.core.task.AsyncListenableTaskExecutor)1 TaskExecutor (org.springframework.core.task.TaskExecutor)1 TaskRejectedException (org.springframework.core.task.TaskRejectedException)1 TaskTimeoutException (org.springframework.core.task.TaskTimeoutException)1