org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor Java Examples

The following examples show how to use org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor. 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: 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 #2
Source File: MessageBrokerConfigurationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void clientOutboundChannelCustomized() {
	ApplicationContext context = loadConfig(CustomConfig.class);

	AbstractSubscribableChannel channel = context.getBean(
			"clientOutboundChannel", AbstractSubscribableChannel.class);

	assertEquals(4, channel.getInterceptors().size());

	ThreadPoolTaskExecutor taskExecutor = context.getBean(
			"clientOutboundChannelExecutor", ThreadPoolTaskExecutor.class);

	assertEquals(21, taskExecutor.getCorePoolSize());
	assertEquals(22, taskExecutor.getMaxPoolSize());
	assertEquals(23, taskExecutor.getKeepAliveSeconds());

	SimpleBrokerMessageHandler broker =
			context.getBean("simpleBrokerMessageHandler", SimpleBrokerMessageHandler.class);
	assertTrue(broker.isPreservePublishOrder());
}
 
Example #3
Source File: ExecutorConfig.java    From youkefu with Apache License 2.0 6 votes vote down vote up
/**
 * 作业平台使用的线程池
 * @return
 */
@Bean(name = "uKeFuTaskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {

	ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
	// 线程池维护线程的最少数量
	poolTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
	// 线程池维护线程的最大数量
	poolTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
	// 线程池所使用的缓冲队列
	poolTaskExecutor.setQueueCapacity(200);
	// 线程池维护线程所允许的空闲时间
	poolTaskExecutor.setKeepAliveSeconds(30);
	poolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
	poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
	return poolTaskExecutor;
}
 
Example #4
Source File: AsyncAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void taskExecutorByBeanType() {
	StaticApplicationContext context = new StaticApplicationContext();

	BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);

	BeanDefinition executorDefinition = new RootBeanDefinition(ThreadPoolTaskExecutor.class);
	executorDefinition.getPropertyValues().add("threadNamePrefix", "testExecutor");
	context.registerBeanDefinition("myExecutor", executorDefinition);

	BeanDefinition targetDefinition =
			new RootBeanDefinition(AsyncAnnotationBeanPostProcessorTests.TestBean.class);
	context.registerBeanDefinition("target", targetDefinition);

	context.refresh();

	ITestBean testBean = context.getBean("target", ITestBean.class);
	testBean.test();
	testBean.await(3000);
	Thread asyncThread = testBean.getThread();
	assertTrue(asyncThread.getName().startsWith("testExecutor"));
	context.close();
}
 
Example #5
Source File: TaskExecutorConfig.java    From batch-scheduler with MIT License 6 votes vote down vote up
@Bean
public TaskExecutor taskExecutor() {

    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    // 设置核心线程数
    executor.setCorePoolSize(10);
    // 设置最大线程数
    executor.setMaxPoolSize(15);
    // 设置队列容量
    executor.setQueueCapacity(20);
    // 设置线程活跃时间(秒)
    executor.setKeepAliveSeconds(60);
    // 设置默认线程名称
    executor.setThreadNamePrefix("batch-task-running-");
    // 设置拒绝策略
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    // 等待所有任务结束后再关闭线程池
    executor.setWaitForTasksToCompleteOnShutdown(true);

    return executor;
}
 
Example #6
Source File: AsyncAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void threadNamePrefix() {
	BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class);
	ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
	executor.setThreadNamePrefix("testExecutor");
	executor.afterPropertiesSet();
	processorDefinition.getPropertyValues().add("executor", executor);
	ConfigurableApplicationContext context = initContext(processorDefinition);

	ITestBean testBean = context.getBean("target", ITestBean.class);
	testBean.test();
	testBean.await(3000);
	Thread asyncThread = testBean.getThread();
	assertTrue(asyncThread.getName().startsWith("testExecutor"));
	context.close();
}
 
Example #7
Source File: AsynExecutorConfig.java    From lion with Apache License 2.0 6 votes vote down vote up
@Bean("asynExecutor")
public Executor AsynExecutor() {

    /**
     * setCorePoolSize核心线程数10:线程池创建时候初始化的线程数
     * setMaxPoolSize最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
     * setQueueCapacity缓冲队列200:用来缓冲执行任务的队列
     * setKeepAliveSeconds允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
     * setThreadNamePrefix线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
     * setRejectedExecutionHandler线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
     */
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(10);
    executor.setMaxPoolSize(20);
    executor.setQueueCapacity(200);
    executor.setKeepAliveSeconds(60);
    executor.setThreadNamePrefix("AsynTaskExecutor-");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    // 执行初始化
    executor.initialize();

    return executor;
}
 
Example #8
Source File: NettyBootstrapFactory.java    From WeCross with Apache License 2.0 6 votes vote down vote up
public static NettyBootstrap build(
        P2PConfig p2pConfig,
        ThreadPoolTaskExecutor threadPool,
        MessageCallBack messageCallBack) {
    System.out.println("Initializing NettyBootstrap ...");

    ChannelHandlerCallBack channelHandlerCallBack = new ChannelHandlerCallBack();
    channelHandlerCallBack.setThreadPool(threadPool);
    channelHandlerCallBack.setCallBack(messageCallBack);

    NettyBootstrap bootstrap = new NettyBootstrap();
    bootstrap.setConfig(p2pConfig);
    bootstrap.setChannelHandlerCallBack(channelHandlerCallBack);

    return bootstrap;
}
 
Example #9
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void threadPoolSizeDefault() {
	String name = "clientInboundChannelExecutor";
	ThreadPoolTaskExecutor executor = this.defaultContext.getBean(name, ThreadPoolTaskExecutor.class);
	assertEquals(Runtime.getRuntime().availableProcessors() * 2, executor.getCorePoolSize());
	// No way to verify queue capacity

	name = "clientOutboundChannelExecutor";
	executor = this.defaultContext.getBean(name, ThreadPoolTaskExecutor.class);
	assertEquals(Runtime.getRuntime().availableProcessors() * 2, executor.getCorePoolSize());

	name = "brokerChannelExecutor";
	executor = this.defaultContext.getBean(name, ThreadPoolTaskExecutor.class);
	assertEquals(0, executor.getCorePoolSize());
	assertEquals(1, executor.getMaxPoolSize());
}
 
Example #10
Source File: P2PServiceConfig.java    From WeCross with Apache License 2.0 6 votes vote down vote up
@Bean
public P2PService newP2PService() {
    ThreadPoolTaskExecutor threadPool =
            ThreadPoolTaskExecutorFactory.build(
                    p2pConfig.getThreadNum(),
                    p2pConfig.getThreadQueueCapacity(),
                    "p2p-callback");
    SeqMapper seqMapper = SeqMapperFactory.build();
    MessageCallBack messageCallback =
            MessageCallbackFactory.build(seqMapper, peerManager, zoneManager);
    NettyBootstrap nettyBootstrap =
            NettyBootstrapFactory.build(p2pConfig, threadPool, messageCallback);
    NettyService nettyService =
            NettyServiceFactory.build(seqMapper, threadPool, nettyBootstrap);

    P2PService p2PService = new P2PService();
    p2PService.setNettyService(nettyService);
    return p2PService;
}
 
Example #11
Source File: ExecutorBeanDefinitionParserTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultExecutor() throws Exception {
	ThreadPoolTaskExecutor executor = this.context.getBean("default", ThreadPoolTaskExecutor.class);
	assertEquals(1, getCorePoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getMaxPoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor));
	assertEquals(60, getKeepAliveSeconds(executor));
	assertEquals(false, getAllowCoreThreadTimeOut(executor));

	FutureTask<String> task = new FutureTask<>(new Callable<String>() {
		@Override
		public String call() throws Exception {
			return "foo";
		}
	});
	executor.execute(task);
	assertEquals("foo", task.get());
}
 
Example #12
Source File: AsyncTaskExecutePool.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    //核心线程池大小
    executor.setCorePoolSize(config.getCorePoolSize());
    //最大线程数
    executor.setMaxPoolSize(config.getMaxPoolSize());
    //队列容量
    executor.setQueueCapacity(config.getQueueCapacity());
    //活跃时间
    executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
    //线程名字前缀
    executor.setThreadNamePrefix("sk-async-");
    // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
    // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
}
 
Example #13
Source File: AsyncConfig.java    From springboot-guide with Apache License 2.0 5 votes vote down vote up
@Bean
public Executor taskExecutor() {
  ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  // 核心线程数
  executor.setCorePoolSize(CORE_POOL_SIZE);
  // 最大线程数
  executor.setMaxPoolSize(MAX_POOL_SIZE);
  // 队列大小
  executor.setQueueCapacity(QUEUE_CAPACITY);
  // 当最大池已满时,此策略保证不会丢失任务请求,但是可能会影响应用程序整体性能。
  executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  executor.setThreadNamePrefix("My ThreadPoolTaskExecutor-");
  executor.initialize();
  return executor;
}
 
Example #14
Source File: EnableAsyncTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
	if (bean instanceof ThreadPoolTaskExecutor) {
		((ThreadPoolTaskExecutor) bean).setThreadNamePrefix("Post-");
	}
	return bean;
}
 
Example #15
Source File: FlowableJobConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(8);
    executor.setMaxPoolSize(8);
    executor.setQueueCapacity(100);
    executor.setThreadNamePrefix("flowable-task-Executor-");
    executor.setAwaitTerminationSeconds(30);
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setAllowCoreThreadTimeOut(true);
    executor.initialize();
    return executor;
}
 
Example #16
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 #17
Source File: SecurityPubSubChannel.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public ThreadPoolTaskExecutor executor() {
    ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
    pool.setCorePoolSize(10);
    pool.setMaxPoolSize(10);
    pool.setWaitForTasksToCompleteOnShutdown(true);
    return pool;
}
 
Example #18
Source File: ThreadPoolTaskExecutorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCorePoolSizeFive_thenFiveThreads() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(5);
    taskExecutor.afterPropertiesSet();

    CountDownLatch countDownLatch = new CountDownLatch(10);
    this.startThreads(taskExecutor, countDownLatch, 10);

    while (countDownLatch.getCount() > 0) {
        Assert.assertEquals(5, taskExecutor.getPoolSize());
    }
}
 
Example #19
Source File: AsyncProcessLoggerConfiguration.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Bean("asyncExecutor")
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(configuration.getFlowableJobExecutorCoreThreads());
    executor.setMaxPoolSize(configuration.getFlowableJobExecutorMaxThreads());
    executor.setQueueCapacity(configuration.getFlowableJobExecutorQueueCapacity());
    executor.initialize();
    return executor;
}
 
Example #20
Source File: ExecutorConfig.java    From SpringBootBucket with MIT License 5 votes vote down vote up
@Bean
public Executor myAsync() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setThreadNamePrefix("MyExecutor-");

    // rejection-policy:当pool已经达到max size的时候,如何处理新任务
    // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
}
 
Example #21
Source File: CommonConfiguration.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Primary
@Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(commonProperties.getExecution().getCorePoolSize());
    executor.setMaxPoolSize(commonProperties.getExecution().getMaxPoolSize());
    executor.setThreadNamePrefix("taskExecutor");
    return executor;
}
 
Example #22
Source File: MainBeanConfig.java    From Cleanstone with MIT License 5 votes vote down vote up
@Bean
public TaskExecutor mcLoginExec() {
    ThreadPoolTaskExecutor taskExecutor = createTaskExecutor(10, "mcLoginExec");
    taskExecutor.initialize();

    return taskExecutor;
}
 
Example #23
Source File: ExecutorServiceConfig.java    From bswen-project with Apache License 2.0 5 votes vote down vote up
@Bean
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(1);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(5);
    executor.setThreadNamePrefix("MyAsync-");
    executor.initialize();
    return executor;
}
 
Example #24
Source File: AsyncConfiguration.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
    log.debug("Creating Async Task Executor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
    executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
    executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
    executor.setThreadNamePrefix("ability-Executor-");
    return new ExceptionHandlingAsyncTaskExecutor(executor);
}
 
Example #25
Source File: SmoothieConfig.java    From spring4ws-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public CpuDataService cpuDataService() {
	ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
	executor.setMaxPoolSize(10);
	executor.setThreadNamePrefix("SmoothieHandler-");
	executor.afterPropertiesSet();

	return new CpuDataService(executor);
}
 
Example #26
Source File: AsyncConfiguration.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
    log.debug("Creating Async Task Executor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
    executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
    executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
    executor.setThreadNamePrefix("j-hipster-registry-Executor-");
    return new ExceptionHandlingAsyncTaskExecutor(executor);
}
 
Example #27
Source File: AsyncConfiguration.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public Executor getAsyncExecutor() {
    log.debug("Creating Async Task Executor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(50);
    executor.setQueueCapacity(10000);
    executor.setThreadNamePrefix("activiti-admin-Executor-");
    executor.initialize();
    return executor;
}
 
Example #28
Source File: AsyncConfiguration.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
    log.debug("Creating Async Task Executor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
    executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
    executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
    executor.setThreadNamePrefix("blog-Executor-");
    return new ExceptionHandlingAsyncTaskExecutor(executor);
}
 
Example #29
Source File: AppConfig.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Configuration for async thread bean
 *
 * More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html
 */
@Bean
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("CsvThread");
    executor.initialize();
    return executor;
}
 
Example #30
Source File: MainBeanConfig.java    From Cleanstone with MIT License 5 votes vote down vote up
@Bean
public TaskExecutor playerExec() {
    ThreadPoolTaskExecutor taskExecutor = createTaskExecutor(10, "playerExec");
    taskExecutor.initialize();

    return taskExecutor;
}