Example usage for org.springframework.core.task SimpleAsyncTaskExecutor SimpleAsyncTaskExecutor

List of usage examples for org.springframework.core.task SimpleAsyncTaskExecutor SimpleAsyncTaskExecutor

Introduction

In this page you can find the example usage for org.springframework.core.task SimpleAsyncTaskExecutor SimpleAsyncTaskExecutor.

Prototype

public SimpleAsyncTaskExecutor() 

Source Link

Document

Create a new SimpleAsyncTaskExecutor with default thread name prefix.

Usage

From source file:org.springframework.batch.core.step.tasklet.AsyncTaskletStepTests.java

private void setUp() throws Exception {

    step = new TaskletStep("stepName");

    ResourcelessTransactionManager transactionManager = new ResourcelessTransactionManager();
    step.setTransactionManager(transactionManager);

    RepeatTemplate chunkTemplate = new RepeatTemplate();
    chunkTemplate.setCompletionPolicy(new SimpleCompletionPolicy(2));
    step.setTasklet(new TestingChunkOrientedTasklet<String>(new ListItemReader<String>(items), itemProcessor,
            itemWriter, chunkTemplate));

    jobRepository = new JobRepositorySupport();
    step.setJobRepository(jobRepository);

    TaskExecutorRepeatTemplate template = new TaskExecutorRepeatTemplate();
    template.setThrottleLimit(throttleLimit);
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    taskExecutor.setConcurrencyLimit(concurrencyLimit);
    template.setTaskExecutor(taskExecutor);
    step.setStepOperations(template);/*from   www . j  a v a  2s .  c o m*/

    step.registerStream(new ItemStreamSupport() {
        private int count = 0;

        @Override
        public void update(ExecutionContext executionContext) {
            super.update(executionContext);
            executionContext.putInt("counter", count++);
        }
    });

}

From source file:org.springframework.batch.core.step.tasklet.SystemCommandTaskletIntegrationTests.java

private void initializeTasklet() {
    tasklet = new SystemCommandTasklet();
    tasklet.setEnvironmentParams(null); // inherit from parent process
    tasklet.setWorkingDirectory(null); // inherit from parent process
    tasklet.setSystemProcessExitCodeMapper(new TestExitCodeMapper());
    tasklet.setTimeout(5000); // long enough timeout
    tasklet.setTerminationCheckInterval(500);
    tasklet.setCommand("invalid command, change value for successful execution");
    tasklet.setInterruptOnCancel(true);/*  ww  w .j ava2  s  .  com*/
    tasklet.setTaskExecutor(new SimpleAsyncTaskExecutor());
}

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

@Before
public void setUp() {

    template = new TaskExecutorRepeatTemplate();
    TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    threadPool.setMaxPoolSize(300);/*from   ww w .  j  ava  2 s  .c o m*/
    threadPool.setCorePoolSize(10);
    threadPool.setQueueCapacity(0);
    threadPool.afterPropertiesSet();
    taskExecutor = threadPool;
    template.setTaskExecutor(taskExecutor);
    template.setThrottleLimit(throttleLimit);

    items = Collections.synchronizedList(new ArrayList<String>());

    callback = new RepeatCallback() {

        private volatile AtomicInteger count = new AtomicInteger(0);

        @Override
        public RepeatStatus doInIteration(RepeatContext context) throws Exception {
            int position = count.incrementAndGet();
            String item = position <= total ? "" + position : null;
            items.add("" + item);
            if (item != null) {
                beBusy();
            }
            /*
             * In a multi-threaded task, one of the callbacks can call
             * FINISHED early, while other threads are still working, and
             * would do more work if the callback was called again. (This
             * happens for instance if there is a failure and you want to
             * retry the work.)
             */
            RepeatStatus result = RepeatStatus.continueIf(position != early && item != null);
            if (position == error) {
                throw new RuntimeException("Planned");
            }
            if (!result.isContinuable()) {
                logger.debug("Returning " + result + " for count=" + position);
            }
            return result;
        }
    };

}

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

@Test
public void testThrottleLimitEarlyFinishOneThread() throws Exception {

    early = 4;/*from  w ww. j  ava 2  s .c  o m*/
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    taskExecutor.setConcurrencyLimit(1);

    // This is kind of slow with only one thread, so reduce size:
    throttleLimit = 10;
    total = 20;

    template.setThrottleLimit(throttleLimit);
    template.setTaskExecutor(taskExecutor);

    template.iterate(callback);
    int frequency = Collections.frequency(items, "null");
    // System.err.println("Frequency: " + frequency);
    // System.err.println("Items: " + items);
    assertEquals(total, items.size() - frequency);
    assertTrue(frequency <= throttleLimit + 1);

}

From source file:org.springframework.cloud.sleuth.instrument.web.client.MultipleAsyncRestTemplateTests.java

public CustomAsyncClientHttpRequestFactory() {
    this.factory.setTaskExecutor(new SimpleAsyncTaskExecutor());
}

From source file:org.springframework.data.mongodb.core.messaging.DefaultMessageListenerContainer.java

/**
 * Create a new {@link DefaultMessageListenerContainer}.
 *
 * @param template must not be {@literal null}.
 *//*from   ww w  .j av a  2  s.c  o  m*/
public DefaultMessageListenerContainer(MongoTemplate template) {
    this(template, new SimpleAsyncTaskExecutor());
}

From source file:org.springframework.data.redis.listener.SubscriptionConnectionTests.java

@Test
public void testStopMessageListenerContainers() throws Exception {
    // Grab all 8 connections from the pool. They should be released on
    // container stop
    for (int i = 0; i < 8; i++) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setBeanName("container" + i);
        container.addMessageListener(new MessageListenerAdapter(handler),
                Arrays.asList(new ChannelTopic(CHANNEL)));
        container.setTaskExecutor(new SyncTaskExecutor());
        container.setSubscriptionExecutor(new SimpleAsyncTaskExecutor());
        container.afterPropertiesSet();/*ww  w .  j  ava  2s.  com*/
        container.start();

        if (connectionFactory instanceof JedisConnectionFactory) {
            // Need to sleep shortly as jedis cannot deal propery with multiple repsonses within one connection
            // @see https://github.com/xetorthio/jedis/issues/186
            Thread.sleep(100);
        }

        container.stop();
        containers.add(container);
    }

    // verify we can now get a connection from the pool
    RedisConnection connection = connectionFactory.getConnection();
    connection.close();
}

From source file:org.springframework.data.redis.listener.SubscriptionConnectionTests.java

@Test
public void testRemoveLastListener() throws Exception {
    // Grab all 8 connections from the pool
    MessageListener listener = new MessageListenerAdapter(handler);
    for (int i = 0; i < 8; i++) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setBeanName("container" + i);
        container.addMessageListener(listener, Arrays.asList(new ChannelTopic(CHANNEL)));
        container.setTaskExecutor(new SyncTaskExecutor());
        container.setSubscriptionExecutor(new SimpleAsyncTaskExecutor());
        container.afterPropertiesSet();/* ww  w  .  j av  a2  s . c  o  m*/
        container.start();
        containers.add(container);
    }

    // Removing the sole listener from the container should free up a
    // connection
    containers.get(0).removeMessageListener(listener);

    // verify we can now get a connection from the pool
    RedisConnection connection = connectionFactory.getConnection();
    connection.close();
}

From source file:org.springframework.data.redis.listener.SubscriptionConnectionTests.java

@Test
public void testStopListening() throws InterruptedException {
    // Grab all 8 connections from the pool.
    MessageListener listener = new MessageListenerAdapter(handler);
    for (int i = 0; i < 8; i++) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setBeanName("container" + i);
        container.addMessageListener(listener, Arrays.asList(new ChannelTopic(CHANNEL)));
        container.setTaskExecutor(new SyncTaskExecutor());
        container.setSubscriptionExecutor(new SimpleAsyncTaskExecutor());
        container.afterPropertiesSet();/*from w ww  .jav  a  2 s  .c o m*/
        container.start();
        containers.add(container);
    }

    // Unsubscribe all listeners from all topics, freeing up a connection
    containers.get(0).removeMessageListener(null, Arrays.asList(new Topic[] {}));

    // verify we can now get a connection from the pool
    RedisConnection connection = connectionFactory.getConnection();
    connection.close();
}

From source file:org.springframework.integration.jms.ChannelPublishingJmsMessageListenerTests.java

private void startBackgroundReplier(final PollableChannel channel) {
    new SimpleAsyncTaskExecutor().execute(() -> {
        Message<?> request = channel.receive(50000);
        Message<?> reply = new GenericMessage<String>(((String) request.getPayload()).toUpperCase());
        ((MessageChannel) request.getHeaders().getReplyChannel()).send(reply, 5000);
    });/*  ww w  .  ja v  a 2s . c o m*/
}