org.springframework.core.task.AsyncTaskExecutor Java Examples

The following examples show how to use org.springframework.core.task.AsyncTaskExecutor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebAsyncManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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<Object>(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();
}
 
Example #2
Source File: WebAsyncManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void startCallableProcessingWithAsyncTask() throws Exception {
	AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
	given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest);

	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).addErrorHandler(any(Consumer.class));
	verify(this.asyncWebRequest).addCompletionHandler(any(Runnable.class));
	verify(this.asyncWebRequest).startAsync();
}
 
Example #3
Source File: WebAsyncManagerTimeoutTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void startCallableProcessingTimeoutAndCheckThreadInterrupted() throws Exception {

	StubCallable callable = new StubCallable();
	Future future = mock(Future.class);

	AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
	when(executor.submit(any(Runnable.class))).thenReturn(future);

	this.asyncManager.setTaskExecutor(executor);
	this.asyncManager.startCallableProcessing(callable);

	this.asyncWebRequest.onTimeout(ASYNC_EVENT);

	assertTrue(this.asyncManager.hasConcurrentResult());

	verify(future).cancel(true);
	verifyNoMoreInteractions(future);
}
 
Example #4
Source File: AsyncConfig.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
public AsyncTaskExecutor getAsyncExecutor() {
	ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
	int availableProcessors = Runtime.getRuntime().availableProcessors();
	int corePoolSize = Math.round(availableProcessors * properties.getCoreThreadTimes());
	int maxPoolSize = Math.round(availableProcessors * properties.getMaxThreadTimes());
	int queueCapacity = Math.round(maxPoolSize * properties.getQueueFactors());
	executor.setCorePoolSize(corePoolSize);
	executor.setMaxPoolSize(maxPoolSize);
	executor.setQueueCapacity(queueCapacity);
	executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
	executor.setThreadNamePrefix(properties.getThreadNamePrefix());
	executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
	executor.initialize();
	log.info("async executor is already now!");
	log.info(
		"async config:corePoolSize-{}, maxPoolSize-{}, queueCapacity-{}, keepAliveSeconds-{}, threadNamePrefix-{}",
		corePoolSize, maxPoolSize, queueCapacity, properties.getKeepAliveSeconds(), properties
			.getThreadNamePrefix());
	return executor;
}
 
Example #5
Source File: AsyncExecutionAspectSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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)
 */
@Nullable
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.get();
		}
		if (targetExecutor == null) {
			return null;
		}
		executor = (targetExecutor instanceof AsyncListenableTaskExecutor ?
				(AsyncListenableTaskExecutor) targetExecutor : new TaskExecutorAdapter(targetExecutor));
		this.executors.put(method, executor);
	}
	return executor;
}
 
Example #6
Source File: SimpleMessageListenerContainer.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default TaskExecutor. Called if no explicit TaskExecutor has been
 * specified.
 * <p>
 * The default implementation builds a
 * {@link org.springframework.core.task.SimpleAsyncTaskExecutor} with the specified
 * bean name (or the class name, if no bean name specified) as thread name prefix.
 * @return a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} configured
 * with the thread name prefix
 * @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String)
 */
protected AsyncTaskExecutor createDefaultTaskExecutor() {
	String beanName = getBeanName();
	ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
	threadPoolTaskExecutor.setThreadNamePrefix(
			beanName != null ? beanName + "-" : DEFAULT_THREAD_NAME_PREFIX);
	int spinningThreads = this.getRegisteredQueues().size();

	if (spinningThreads > 0) {
		threadPoolTaskExecutor
				.setCorePoolSize(spinningThreads * DEFAULT_WORKER_THREADS);

		int maxNumberOfMessagePerBatch = getMaxNumberOfMessages() != null
				? getMaxNumberOfMessages() : DEFAULT_MAX_NUMBER_OF_MESSAGES;
		threadPoolTaskExecutor
				.setMaxPoolSize(spinningThreads * (maxNumberOfMessagePerBatch + 1));
	}

	// No use of a thread pool executor queue to avoid retaining message to long in
	// memory
	threadPoolTaskExecutor.setQueueCapacity(0);
	threadPoolTaskExecutor.afterPropertiesSet();

	return threadPoolTaskExecutor;

}
 
Example #7
Source File: AsyncExecutionAspectSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Delegate for actually executing the given task with the chosen executor.
 * @param task the task to execute
 * @param executor the chosen executor
 * @param returnType the declared return type (potentially a {@link Future} variant)
 * @return the execution result (potentially a corresponding {@link Future} handle)
 */
@Nullable
protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) {
	if (CompletableFuture.class.isAssignableFrom(returnType)) {
		return CompletableFuture.supplyAsync(() -> {
			try {
				return task.call();
			}
			catch (Throwable ex) {
				throw new CompletionException(ex);
			}
		}, executor);
	}
	else if (ListenableFuture.class.isAssignableFrom(returnType)) {
		return ((AsyncListenableTaskExecutor) executor).submitListenable(task);
	}
	else if (Future.class.isAssignableFrom(returnType)) {
		return executor.submit(task);
	}
	else {
		executor.submit(task);
		return null;
	}
}
 
Example #8
Source File: AsyncExecutionAspectSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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)
 */
@Nullable
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.get();
		}
		if (targetExecutor == null) {
			return null;
		}
		executor = (targetExecutor instanceof AsyncListenableTaskExecutor ?
				(AsyncListenableTaskExecutor) targetExecutor : new TaskExecutorAdapter(targetExecutor));
		this.executors.put(method, executor);
	}
	return executor;
}
 
Example #9
Source File: PreservesExecutionContextExecutorStrategyTest.java    From spring-cloud-ribbon-extensions with Apache License 2.0 6 votes vote down vote up
@Test
public void postProcessAfterInitialization() throws Exception {
    assertThat(processor.postProcessAfterInitialization(mock(Executor.class), toBeExcluded).getClass(),
            not(equalTo(ContextAwareExecutor.class)));
    //concurrent
    assertThat(processor.postProcessAfterInitialization(mock(Executor.class), beanName).getClass(),
            equalTo(ContextAwareExecutor.class));
    assertThat(processor.postProcessAfterInitialization(mock(ExecutorService.class), beanName).getClass(),
            equalTo(ContextAwareExecutorService.class));
    assertThat(processor.postProcessAfterInitialization(mock(ScheduledExecutorService.class), beanName).getClass(),
            equalTo(ContextAwareScheduledExecutorService.class));

    //spring
    assertThat(processor.postProcessAfterInitialization(mock(TaskScheduler.class), beanName).getClass(),
            equalTo(ContextAwareTaskScheduler.class));
    assertThat(processor.postProcessAfterInitialization(new ThreadPoolTaskExecutor(), beanName).getClass(),
            equalTo(ContextAwareThreadPoolTaskExecutor.class));
    assertThat(processor.postProcessAfterInitialization(new ThreadPoolTaskScheduler(), beanName).getClass(),
            equalTo(ContextAwareThreadPoolTaskScheduler.class));
    assertThat(processor.postProcessAfterInitialization(mock(AsyncListenableTaskExecutor.class), beanName).getClass(),
            equalTo(ContextAwareAsyncListenableTaskExecutor.class));
    assertThat(processor.postProcessAfterInitialization(mock(AsyncTaskExecutor.class), beanName).getClass(),
            equalTo(ContextAwareAsyncTaskExecutor.class));
    assertThat(processor.postProcessAfterInitialization(mock(SchedulingTaskExecutor.class), beanName).getClass(),
            equalTo(ContextAwareSchedulingTaskExecutor.class));
}
 
Example #10
Source File: AsyncWebProcessorBuilder.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public ProgressAsyncWebProcessor buildProgressAsyncWebProcessor(){
		if(asyncTaskExecutor==null){
			asyncTaskExecutor = Springs.getInstance().getBean(AsyncTaskExecutor.class);
		}
		Assert.hasText(asynCallback);
//		Assert.hasText(progressCallback);
		response.setContentType(contentType);
		DefaultProgressAsyncWebProcessor processor = null;
		try {
			if(useCompletableFeture){
				processor = new CompletableProgressAsyncWebProcessor(response.getWriter(), messageTunnel, asyncTaskExecutor, /*progressCallback, */asynCallback);
			}else{
				processor = new DefaultProgressAsyncWebProcessor(response.getWriter(), messageTunnel, asyncTaskExecutor, /*progressCallback, */asynCallback);
			}
			processor.setSleepTime(flushInMilliSecond);
			processor.setWriteEmptyMessage(writeEmptyMessage);
		} catch (IOException e) {
			throw new BaseException("build ProgressAsyncWebProcessor error: " + e.getMessage());
		}
		return processor;
	}
 
Example #11
Source File: WebAsyncManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void startCallableProcessingWithAsyncTask() throws Exception {
	AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
	given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest);

	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).addErrorHandler(any(Consumer.class));
	verify(this.asyncWebRequest).addCompletionHandler(any(Runnable.class));
	verify(this.asyncWebRequest).startAsync();
}
 
Example #12
Source File: AsyncExecutionAspectSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Delegate for actually executing the given task with the chosen executor.
 * @param task the task to execute
 * @param executor the chosen executor
 * @param returnType the declared return type (potentially a {@link Future} variant)
 * @return the execution result (potentially a corresponding {@link Future} handle)
 */
protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) {
	if (completableFuturePresent) {
		Future<Object> result = CompletableFutureDelegate.processCompletableFuture(returnType, task, executor);
		if (result != null) {
			return result;
		}
	}
	if (ListenableFuture.class.isAssignableFrom(returnType)) {
		return ((AsyncListenableTaskExecutor) executor).submitListenable(task);
	}
	else if (Future.class.isAssignableFrom(returnType)) {
		return executor.submit(task);
	}
	else {
		executor.submit(task);
		return null;
	}
}
 
Example #13
Source File: AsyncExecutionAspectSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Delegate for actually executing the given task with the chosen executor.
 * @param task the task to execute
 * @param executor the chosen executor
 * @param returnType the declared return type (potentially a {@link Future} variant)
 * @return the execution result (potentially a corresponding {@link Future} handle)
 */
protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) {
	if (completableFuturePresent) {
		Future<Object> result = CompletableFutureDelegate.processCompletableFuture(returnType, task, executor);
		if (result != null) {
			return result;
		}
	}
	if (ListenableFuture.class.isAssignableFrom(returnType)) {
		return ((AsyncListenableTaskExecutor) executor).submitListenable(task);
	}
	else if (Future.class.isAssignableFrom(returnType)) {
		return executor.submit(task);
	}
	else {
		executor.submit(task);
		return null;
	}
}
 
Example #14
Source File: ExecutorBeanPostProcessor.java    From elasticactors with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException {
    if (bean instanceof LazyTraceThreadPoolTaskExecutor
            || bean instanceof TraceableScheduledExecutorService
            || bean instanceof TraceableExecutorService
            || bean instanceof LazyTraceAsyncTaskExecutor
            || bean instanceof LazyTraceExecutor) {
        log.info("Bean is already instrumented " + beanName);
        return bean;
    }
    if (bean instanceof ThreadPoolTaskExecutor) {
        return wrapThreadPoolTaskExecutor(bean);
    } else if (bean instanceof ScheduledExecutorService) {
        return wrapScheduledExecutorService(bean);
    } else if (bean instanceof ExecutorService) {
        return wrapExecutorService(bean);
    } else if (bean instanceof AsyncTaskExecutor) {
        return wrapAsyncTaskExecutor(bean);
    } else if (bean instanceof Executor) {
        return wrapExecutor(bean);
    }
    return bean;
}
 
Example #15
Source File: AsyncConfiguration.java    From download-using-streaming-response-body with MIT License 5 votes vote down vote up
@Override
@Bean (name = "taskExecutor")
public AsyncTaskExecutor getAsyncExecutor() {
    log.debug("Creating Async Task Executor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(5);
    executor.setMaxPoolSize(10);
    executor.setQueueCapacity(25);
    return executor;
}
 
Example #16
Source File: AsyncConfig.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Bean(name = "pollableTaskExecutor")
public AsyncTaskExecutor getPollableTaskExecutor() {
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setBeanName("pollableTask");
    threadPoolTaskExecutor.setCorePoolSize(5);
    threadPoolTaskExecutor.setMaxPoolSize(30);
    threadPoolTaskExecutor.initialize();

    return new DelegatingSecurityContextAsyncTaskExecutor(threadPoolTaskExecutor);
}
 
Example #17
Source File: TasksAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get a task executor for executing tasks asynchronously that don't need to be scheduled at a recurring rate.
 *
 * @param tasksExecutorPoolProperties The properties for the task executor thread pool
 * @return The task executor the system to use
 */
@Bean
@ConditionalOnMissingBean(name = "genieAsyncTaskExecutor")
public AsyncTaskExecutor genieAsyncTaskExecutor(final TasksExecutorPoolProperties tasksExecutorPoolProperties) {
    final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(tasksExecutorPoolProperties.getSize());
    executor.setThreadNamePrefix(tasksExecutorPoolProperties.getThreadNamePrefix());
    return executor;
}
 
Example #18
Source File: WebAsyncManagerTimeoutTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}
 
Example #19
Source File: AppConfig.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public AsyncTaskExecutor intermediateBuilderExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(intermediateCorePoolSize);
    executor.setQueueCapacity(intermediateQueueCapacity);
    executor.setThreadNamePrefix("intermediateBuilderExecutor-");
    executor.setTaskDecorator(new MDCCleanerTaskDecorator());
    executor.initialize();
    return executor;
}
 
Example #20
Source File: WebAsyncTask.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a {@code WebAsyncTask} with a timeout value, an executor instance, and a Callable.
 * @param timeout timeout value in milliseconds; ignored if {@code null}
 * @param executor the executor to use
 * @param callable the callable for concurrent handling
 */
public WebAsyncTask(@Nullable Long timeout, AsyncTaskExecutor executor, Callable<V> callable) {
	this(callable);
	Assert.notNull(executor, "Executor must not be null");
	this.executor = executor;
	this.timeout = timeout;
}
 
Example #21
Source File: ExecutorBeanPostProcessor.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private Object wrapAsyncTaskExecutor(Object bean) {
    AsyncTaskExecutor executor = (AsyncTaskExecutor) bean;
    boolean classFinal = Modifier.isFinal(bean.getClass().getModifiers());
    boolean methodsFinal = anyFinalMethods(executor, AsyncTaskExecutor.class);
    boolean cglibProxy = !classFinal && !methodsFinal;
    return createAsyncTaskExecutorProxy(bean, cglibProxy, executor);
}
 
Example #22
Source File: WebAsyncManagerErrorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #23
Source File: WebAsyncManagerTimeoutTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #24
Source File: PetClinicApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public EntityManagerFactoryBuilderCustomizer customEntityManagerFactoryBootstrapExecutorCustomizer(
        Map<String, AsyncTaskExecutor> taskExecutors) {
    return (builder) -> {
        builder.setBootstrapExecutor(new ConcurrentTaskExecutor());
    };
}
 
Example #25
Source File: PreservesExecutionContextExecutorStrategy.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (bean instanceof Executor || bean instanceof TaskScheduler) {
        if (properties.getExecutor().accept(beanName)) {
            if (bean instanceof AsyncListenableTaskExecutor && bean instanceof SchedulingTaskExecutor && bean instanceof TaskScheduler) {
                log.info("Context propagation enabled for ~ThreadPoolTaskScheduler [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareThreadPoolTaskScheduler((AsyncListenableTaskExecutor) bean, (SchedulingTaskExecutor) bean, (TaskScheduler) bean);
            } else if (bean instanceof AsyncListenableTaskExecutor && bean instanceof SchedulingTaskExecutor) {
                log.info("Context propagation enabled for ~ThreadPoolTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareThreadPoolTaskExecutor((AsyncListenableTaskExecutor) bean, (SchedulingTaskExecutor) bean);
            } else if (bean instanceof TaskScheduler) {
                log.info("Context propagation enabled for TaskScheduler [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareTaskScheduler((TaskScheduler) bean);
            } else if (bean instanceof SchedulingTaskExecutor) {
                log.info("Context propagation enabled for SchedulingTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareSchedulingTaskExecutor((SchedulingTaskExecutor) bean);
            } else if (bean instanceof AsyncListenableTaskExecutor) {
                log.info("Context propagation enabled for AsyncListenableTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareAsyncListenableTaskExecutor((AsyncListenableTaskExecutor) bean);
            } else if (bean instanceof AsyncTaskExecutor) {
                log.info("Context propagation enabled for AsyncTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareAsyncTaskExecutor((AsyncTaskExecutor) bean);
            } else if (bean instanceof ScheduledExecutorService) {
                log.info("Context propagation enabled for ScheduledExecutorService [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareScheduledExecutorService((ScheduledExecutorService) bean);
            } else if (bean instanceof ExecutorService) {
                log.info("Context propagation enabled for ExecutorService [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareExecutorService((ExecutorService) bean);
            } else {
                log.info("Context propagation enabled for Executor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareExecutor((Executor) bean);
            }
        } else {
            log.debug("Context propagation disabled for Executor [{}]", beanName);
        }
    }
    return bean;
}
 
Example #26
Source File: AsyncMvcConfiguration.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Bean(MVC_ASYNC_TASK_BEAN_NAME)
@ConditionalOnMissingBean(name=AsyncMvcConfiguration.MVC_ASYNC_TASK_BEAN_NAME)
@Primary
   public AsyncTaskExecutor mvcAsyncTaskExecutor() {
       ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
       executor.setCorePoolSize(mvcAsyncProperties.getCorePoolSize());
       executor.setMaxPoolSize(mvcAsyncProperties.getMaxPoolSize());
       executor.setQueueCapacity(mvcAsyncProperties.getQueueCapacity());
       return executor;
   }
 
Example #27
Source File: EventsAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * A multicast event publisher to replace the default one used by Spring via the ApplicationContext.
 *
 * @param syncTaskExecutor  The synchronous task executor to use
 * @param asyncTaskExecutor The asynchronous task executor to use
 * @return The application event multicaster to use
 */
@Bean
@ConditionalOnMissingBean(GenieEventBus.class)
public GenieEventBusImpl applicationEventMulticaster(
    @Qualifier("genieSyncTaskExecutor") final SyncTaskExecutor syncTaskExecutor,
    @Qualifier("genieAsyncTaskExecutor") final AsyncTaskExecutor asyncTaskExecutor
) {
    final SimpleApplicationEventMulticaster syncMulticaster = new SimpleApplicationEventMulticaster();
    syncMulticaster.setTaskExecutor(syncTaskExecutor);

    final SimpleApplicationEventMulticaster asyncMulticaster = new SimpleApplicationEventMulticaster();
    asyncMulticaster.setTaskExecutor(asyncTaskExecutor);
    return new GenieEventBusImpl(syncMulticaster, asyncMulticaster);
}
 
Example #28
Source File: WebAsyncTask.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the AsyncTaskExecutor to use for concurrent handling,
 * or {@code null} if none specified.
 */
public AsyncTaskExecutor getExecutor() {
	if (this.executor != null) {
		return this.executor;
	}
	else if (this.executorName != null) {
		Assert.state(this.beanFactory != null, "BeanFactory is required to look up an executor bean by name");
		return this.beanFactory.getBean(this.executorName, AsyncTaskExecutor.class);
	}
	else {
		return null;
	}
}
 
Example #29
Source File: AsyncExecutionAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: DefaultAsyncWebProcessor.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public DefaultAsyncWebProcessor(PrintWriter out, AsyncMessageHolder holder, AsyncTaskExecutor asyncTaskExecutor) {
		super();
		this.out = out;
//		this.dataCountPerTask = taskInterval;
		this.asynMessageHolder = holder;
		if(asyncTaskExecutor==null){
			this.asyncTaskExecutor = Springs.getInstance().getBean(AsyncTaskExecutor.class);
			Assert.notNull(this.asyncTaskExecutor, "no asyncTaskExecutor found, please add a asyncTaskExecutor to spring context!");
		}else{
			this.asyncTaskExecutor = asyncTaskExecutor;
		}
	}