Example usage for org.springframework.scheduling.concurrent ThreadPoolTaskExecutor setCorePoolSize

List of usage examples for org.springframework.scheduling.concurrent ThreadPoolTaskExecutor setCorePoolSize

Introduction

In this page you can find the example usage for org.springframework.scheduling.concurrent ThreadPoolTaskExecutor setCorePoolSize.

Prototype

public void setCorePoolSize(int corePoolSize) 

Source Link

Document

Set the ThreadPoolExecutor's core pool size.

Usage

From source file:org.finra.dm.service.config.ServiceSpringModuleConfig.java

/**
 * Returns an Async "task" executor which is also a normal "executor". This is being wired into Activity via the job executor bean. It is also being used by
 * the "@EnableAsync" annotation and the fact that this class implements AsyncConfigurer. That way, all methods annotated with "@Async" will be executed
 * asynchronously by this executor. Thus, we have a shared thread pool that handles both Async method calls as well as Activiti asynchronous job executions
 * (e.g. timers, messages, etc.)./* ww  w .  j a  v a  2  s.  co m*/
 *
 * @return the async task executor.
 */
@Override
@Bean // This will call the "initialize" method of the ThreadPoolTaskExecutor automatically.
public TaskExecutor getAsyncExecutor() {
    // Create a Spring thread pool "task" executor that is backed by a JDK Thread Pool Executor.
    // Use the environment to make the key thread pool parameters configurable although changing them would require a server restart.
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(
            configurationHelper.getProperty(ConfigurationValue.THREAD_POOL_CORE_POOL_SIZE, Integer.class));
    executor.setMaxPoolSize(
            configurationHelper.getProperty(ConfigurationValue.THREAD_POOL_MAX_POOL_SIZE, Integer.class));
    executor.setKeepAliveSeconds(
            configurationHelper.getProperty(ConfigurationValue.THREAD_POOL_KEEP_ALIVE_SECS, Integer.class));
    return executor;
}

From source file:org.finra.herd.service.config.ServiceSpringModuleConfig.java

/**
 * Activiti's dedicated TaskExecutor bean definition.
 *
 * @return TaskExecutor/*from www .j ava 2  s .  c  o  m*/
 */
@Bean
public TaskExecutor activitiTaskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(configurationHelper
            .getProperty(ConfigurationValue.ACTIVITI_THREAD_POOL_CORE_POOL_SIZE, Integer.class));
    taskExecutor.setMaxPoolSize(configurationHelper
            .getProperty(ConfigurationValue.ACTIVITI_THREAD_POOL_MAX_POOL_SIZE, Integer.class));
    taskExecutor.setKeepAliveSeconds(configurationHelper
            .getProperty(ConfigurationValue.ACTIVITI_THREAD_POOL_KEEP_ALIVE_SECS, Integer.class));
    taskExecutor.setQueueCapacity(configurationHelper
            .getProperty(ConfigurationValue.ACTIVITI_THREAD_POOL_QUEUE_CAPACITY, Integer.class));
    return taskExecutor;
}

From source file:org.flockdata.helper.ExecutorHelper.java

public static Executor getExecutor(String name, String poolSize, int qCapacity) {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    String vals[] = StringUtils.split(poolSize, "-");

    executor.setCorePoolSize(Integer.parseInt(vals[0]));
    if (vals.length == 2)
        executor.setMaxPoolSize(Integer.parseInt(vals[1]));
    else/*from  ww  w .  j  a va2s  .  c  o m*/
        executor.setMaxPoolSize(Integer.parseInt(vals[0]));
    executor.setQueueCapacity(qCapacity);
    executor.setThreadNamePrefix(name + "-");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor.getThreadPoolExecutor();
}

From source file:org.springframework.batch.core.test.step.FaultTolerantStepFactoryBeanIntegrationTests.java

@Before
public void setUp() throws Exception {

    writer = new SkipWriterStub(dataSource);
    processor = new SkipProcessorStub(dataSource);

    factory = new FaultTolerantStepFactoryBean<String, String>();

    factory.setBeanName("stepName");
    factory.setTransactionManager(transactionManager);
    factory.setJobRepository(repository);
    factory.setCommitInterval(3);//w  w  w  .  ja v a  2  s. co m
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(3);
    taskExecutor.setMaxPoolSize(6);
    taskExecutor.setQueueCapacity(0);
    taskExecutor.afterPropertiesSet();
    factory.setTaskExecutor(taskExecutor);

    JdbcTestUtils.deleteFromTables(new JdbcTemplate(dataSource), "ERROR_LOG");

}

From source file:org.springframework.batch.core.test.step.FaultTolerantStepFactoryBeanRollbackIntegrationTests.java

@Test
public void testMultithreadedSkipInWriter() throws Throwable {

    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(3);
    taskExecutor.setMaxPoolSize(6);//from w w  w  . j  a  va 2  s  .  com
    taskExecutor.setQueueCapacity(0);
    taskExecutor.afterPropertiesSet();
    factory.setTaskExecutor(taskExecutor);

    @SuppressWarnings("unchecked")
    Map<Class<? extends Throwable>, Boolean> skippable = getExceptionMap(Exception.class);
    factory.setSkippableExceptionClasses(skippable);

    jobExecution = repository.createJobExecution("skipJob", new JobParameters());

    for (int i = 0; i < MAX_COUNT; i++) {

        if (i % 100 == 0) {
            logger.info("Starting step: " + i);
        }

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        assertEquals(0, JdbcTestUtils.countRowsInTable(jdbcTemplate, "ERROR_LOG"));

        try {

            SkipReaderStub reader = new SkipReaderStub();
            reader.clear();
            reader.setItems("1", "2", "3", "4", "5");
            factory.setItemReader(reader);
            writer.clear();
            factory.setItemWriter(writer);
            processor.clear();
            factory.setItemProcessor(processor);

            writer.setFailures("1", "2", "3", "4", "5");

            Step step = factory.getObject();

            stepExecution = jobExecution.createStepExecution(factory.getName());
            repository.add(stepExecution);
            step.execute(stepExecution);
            assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());

            assertEquals("[]", writer.getCommitted().toString());
            assertEquals("[]", processor.getCommitted().toString());
            List<String> processed = new ArrayList<String>(processor.getProcessed());
            Collections.sort(processed);
            assertEquals("[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]", processed.toString());
            assertEquals(5, stepExecution.getSkipCount());

        } catch (Throwable e) {
            logger.info("Failed on iteration " + i + " of " + MAX_COUNT);
            throw e;
        }

    }

}

From source file:org.springframework.batch.core.test.step.MapRepositoryFaultTolerantStepFactoryBeanRollbackTests.java

@SuppressWarnings("unchecked")
@Before//from   w w w .ja  va  2  s  . c  om
public void setUp() throws Exception {

    reader = new SkipReaderStub();
    writer = new SkipWriterStub();
    processor = new SkipProcessorStub();

    factory = new FaultTolerantStepFactoryBean<String, String>();

    factory.setTransactionManager(transactionManager);
    factory.setBeanName("stepName");
    factory.setCommitInterval(3);
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(3);
    taskExecutor.setMaxPoolSize(6);
    taskExecutor.setQueueCapacity(0);
    taskExecutor.afterPropertiesSet();
    factory.setTaskExecutor(taskExecutor);

    factory.setSkipLimit(10);
    factory.setSkippableExceptionClasses(getExceptionMap(Exception.class));

}

From source file:org.springframework.batch.core.test.step.MapRepositoryFaultTolerantStepFactoryBeanTests.java

@Before
public void setUp() throws Exception {

    reader = new SkipReaderStub();
    writer = new SkipWriterStub();
    processor = new SkipProcessorStub();

    factory = new FaultTolerantStepFactoryBean<String, String>();

    factory.setBeanName("stepName");
    factory.setTransactionManager(transactionManager);
    factory.setCommitInterval(3);/*from w  ww .j  a va 2  s .  com*/
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(3);
    taskExecutor.setMaxPoolSize(6);
    taskExecutor.setQueueCapacity(0);
    taskExecutor.afterPropertiesSet();
    factory.setTaskExecutor(taskExecutor);

}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Test
public void testThrottleLimitEarlyFinishThreadStarvation() throws Exception {

    early = 2;//from   w ww.  jav a2  s .c  om
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    // Set the concurrency limit below the throttle limit for possible
    // starvation condition
    taskExecutor.setMaxPoolSize(20);
    taskExecutor.setCorePoolSize(10);
    taskExecutor.setQueueCapacity(0);
    // This is the most sensible setting, otherwise the bookkeeping in
    // ResultHolderResultQueue gets out of whack when tasks are aborted.
    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    taskExecutor.afterPropertiesSet();
    template.setTaskExecutor(taskExecutor);

    template.iterate(callback);
    int frequency = Collections.frequency(items, "null");
    // System.err.println("Frequency: " + frequency);
    // System.err.println("Items: " + items);
    // Extra tasks will be submitted before the termination is detected
    assertEquals(total, items.size() - frequency);
    assertTrue(frequency <= throttleLimit + 1);

    taskExecutor.destroy();

}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

private CompositeExecutor compositeExecutor() {
    ThreadPoolTaskExecutor ioExec = new ThreadPoolTaskExecutor();
    ioExec.setCorePoolSize(2);
    ioExec.setMaxPoolSize(4);/*from  w  ww . jav  a  2s  .c  o  m*/
    ioExec.setQueueCapacity(0);
    ioExec.setThreadNamePrefix("io-");
    ioExec.setRejectedExecutionHandler(new AbortPolicy());
    ioExec.initialize();
    ThreadPoolTaskExecutor assemblerExec = new ThreadPoolTaskExecutor();
    assemblerExec.setCorePoolSize(2);
    assemblerExec.setMaxPoolSize(5);
    assemblerExec.setQueueCapacity(0);
    assemblerExec.setThreadNamePrefix("assembler-");
    assemblerExec.setRejectedExecutionHandler(new AbortPolicy());
    assemblerExec.initialize();
    return new CompositeExecutor(ioExec, assemblerExec);
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void int3453RaceTest() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    final CountDownLatch connectionLatch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override//from ww  w. ja v a  2  s  .  co  m
        public void publishEvent(ApplicationEvent event) {
            if (event instanceof TcpConnectionOpenEvent) {
                connectionLatch.countDown();
            }
        }

        @Override
        public void publishEvent(Object event) {

        }

    });
    final CountDownLatch assemblerLatch = new CountDownLatch(1);
    final AtomicReference<Thread> assembler = new AtomicReference<Thread>();
    factory.registerListener(new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                assembler.set(Thread.currentThread());
                assemblerLatch.countDown();
            }
            return false;
        }

    });
    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.setCorePoolSize(3); // selector, reader, assembler
    te.setMaxPoolSize(3);
    te.setQueueCapacity(0);
    te.initialize();
    factory.setTaskExecutor(te);
    factory.start();
    TestingUtilities.waitListening(factory, 10000L);
    int port = factory.getPort();
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    assertTrue(connectionLatch.await(10, TimeUnit.SECONDS));

    TcpNioConnection connection = (TcpNioConnection) TestUtils
            .getPropertyValue(factory, "connections", Map.class).values().iterator().next();
    Log logger = spy(TestUtils.getPropertyValue(connection, "logger", Log.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(connection);
    dfa.setPropertyValue("logger", logger);

    ChannelInputStream cis = spy(
            TestUtils.getPropertyValue(connection, "channelInputStream", ChannelInputStream.class));
    dfa.setPropertyValue("channelInputStream", cis);

    final CountDownLatch readerLatch = new CountDownLatch(4); // 3 dataAvailable, 1 continuing
    final CountDownLatch readerFinishedLatch = new CountDownLatch(1);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            // delay the reader thread resetting writingToPipe
            readerLatch.await(10, TimeUnit.SECONDS);
            Thread.sleep(100);
            readerFinishedLatch.countDown();
            return null;
        }
    }).when(cis).write(any(ByteBuffer.class));

    doReturn(true).when(logger).isTraceEnabled();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("checking data avail"));

    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("Nio assembler continuing"));

    socket.getOutputStream().write("foo\r\n".getBytes());

    assertTrue(assemblerLatch.await(10, TimeUnit.SECONDS));
    assertTrue(readerFinishedLatch.await(10, TimeUnit.SECONDS));

    StackTraceElement[] stackTrace = assembler.get().getStackTrace();
    assertThat(Arrays.asList(stackTrace).toString(), not(containsString("ChannelInputStream.getNextBuffer")));
    socket.close();
    factory.stop();
}