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

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

Introduction

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

Prototype

ThreadPoolTaskExecutor

Source Link

Usage

From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java

@Test
public void testImportFrequencyList_LeftoversFromBatch() {
    ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor());
    taskExecutorSpy.setCorePoolSize(4);/*from   w  w  w .  j a  v  a 2  s. c  om*/
    taskExecutorSpy.setMaxPoolSize(4);
    taskExecutorSpy.setQueueCapacity(100);
    taskExecutorSpy.setKeepAliveSeconds(1);
    taskExecutorSpy.setAllowCoreThreadTimeOut(true);
    taskExecutorSpy.initialize();

    FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl();
    frequencyListImporterImpl.setTaskExecutor(taskExecutorSpy);

    Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount");
    ReflectionUtils.makeAccessible(rowUpdateCountField);
    AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);

    assertEquals(0, rowUpdateCountFromObject.intValue());

    Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount");
    ReflectionUtils.makeAccessible(rowInsertCountField);
    AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField,
            frequencyListImporterImpl);

    assertEquals(0, rowInsertCountFromObject.intValue());

    WordDao wordDaoMock = mock(WordDao.class);
    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);
    int persistenceBatchSizeToSet = 3;
    int concurrencyBatchSizeToSet = 2;

    frequencyListImporterImpl.setWordDao(wordDaoMock);
    frequencyListImporterImpl.setPersistenceBatchSize(persistenceBatchSizeToSet);
    frequencyListImporterImpl.setConcurrencyBatchSize(concurrencyBatchSizeToSet);

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100);
    Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200);
    Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300);
    Word word4 = new Word(new WordId("super", PartOfSpeechType.ADJECTIVE), 400);
    Word word5 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 500);
    List<Word> wordsToReturn = new ArrayList<Word>();
    wordsToReturn.add(word1);
    wordsToReturn.add(word2);
    wordsToReturn.add(word3);
    wordsToReturn.add(word4);
    wordsToReturn.add(word5);
    FrequencyFileParser fileParserMock = mock(FrequencyFileParser.class);
    when(fileParserMock.parseFile()).thenReturn(wordsToReturn);

    frequencyListImporterImpl.setFileParser(fileParserMock);

    Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    Word wordFromDatabase3 = new Word(new WordId("is", PartOfSpeechType.ADJECTIVE));

    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);
    when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true);
    when(wordDaoMock.findByWordString(eq("george"))).thenReturn(Arrays.asList(wordFromDatabase1));
    when(wordDaoMock.findByWordString(eq("belden"))).thenReturn(Arrays.asList(wordFromDatabase2));
    when(wordDaoMock.findByWordString(eq("is"))).thenReturn(

            Arrays.asList(wordFromDatabase3));
    when(wordDaoMock.findByWordString(eq("super"))).thenReturn(null);
    when(wordDaoMock.findByWordString(eq("seriously"))).thenReturn(null);
    when(wordDaoMock.findByWordString(eq("awesome"))).thenReturn(null);

    frequencyListImporterImpl.importFrequencyList();

    assertEquals(100, wordFromDatabase1.getFrequencyWeight());
    assertEquals(200, wordFromDatabase2.getFrequencyWeight());
    assertEquals(300, wordFromDatabase3.getFrequencyWeight());

    rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);
    rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField,
            frequencyListImporterImpl);

    assertEquals(3, rowUpdateCountFromObject.intValue());
    assertEquals(2, rowInsertCountFromObject.intValue());
    verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(2)).updateBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(5)).findByWordString(anyString());
    verify(taskExecutorSpy, times(3)).execute(any(Runnable.class));
}

From source file:com.netflix.genie.core.configs.ServicesConfigTest.java

/**
 * The task executor to use./*from  w w  w .  j a v  a2  s  . com*/
 *
 * @return The task executor to for launching jobs
 */
@Bean
public AsyncTaskExecutor taskExecutor() {
    return new ThreadPoolTaskExecutor();
}

From source file:org.logger.event.web.controller.EventController.java

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(15);/*from  w  w w  .jav  a  2  s. c  o  m*/
    executor.setMaxPoolSize(80);
    executor.setQueueCapacity(200);
    executor.setThreadNamePrefix("eventExecutor");
    executor.initialize();
    return executor;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.ExtenderConfiguration.java

private TaskExecutor createDefaultShutdownTaskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setDaemon(true);//from  w  w w .jav  a2 s .  co m
    taskExecutor.setCorePoolSize(2);
    taskExecutor.setMaxPoolSize(3);
    taskExecutor.setThreadNamePrefix("Gemini Blueprint context shutdown thread");
    taskExecutor.afterPropertiesSet();
    isShutdownTaskExecutorManagedInternally = true;
    return taskExecutor;
}

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.)./*from w w  w .  j  a v  a2 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 a  v  a2s . 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/* w w w . j  a  v a 2s  .  c om*/
        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.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Test
public void testAtomicSendAndReceiveExternalExecutor() throws Exception {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
    final String execName = "make-sure-exec-passed-in";
    exec.setBeanName(execName);//ww w  .  j  av  a2  s  . c o m
    exec.afterPropertiesSet();
    connectionFactory.setExecutor(exec);
    final Field[] fields = new Field[1];
    ReflectionUtils.doWithFields(RabbitTemplate.class, new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            field.setAccessible(true);
            fields[0] = field;
        }
    }, new FieldFilter() {
        public boolean matches(Field field) {
            return field.getName().equals("logger");
        }
    });
    Log logger = Mockito.mock(Log.class);
    when(logger.isTraceEnabled()).thenReturn(true);

    final AtomicBoolean execConfiguredOk = new AtomicBoolean();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String log = (String) invocation.getArguments()[0];
            if (log.startsWith("Message received") && Thread.currentThread().getName().startsWith(execName)) {
                execConfiguredOk.set(true);
            }
            return null;
        }
    }).when(logger).trace(Mockito.anyString());
    final RabbitTemplate template = new RabbitTemplate(connectionFactory);
    ReflectionUtils.setField(fields[0], template, logger);
    template.setRoutingKey(ROUTE);
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive();
    assertEquals(null, reply);

    assertTrue(execConfiguredOk.get());
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerIntegrationTests.java

@Test
public void testSimple() throws Exception {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setThreadNamePrefix("client-");
    executor.afterPropertiesSet();/*from   w w  w.  jav a 2  s .  c  o  m*/
    cf.setExecutor(executor);
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1, Q2);
    container.setConsumersPerQueue(2);
    container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> {
        if ("foo".equals(in) || "bar".equals(in)) {
            return in.toUpperCase();
        } else {
            return null;
        }
    }));
    container.setBeanName("simple");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    assertEquals("FOO", template.convertSendAndReceive(Q1, "foo"));
    assertEquals("BAR", template.convertSendAndReceive(Q2, "bar"));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    template.stop();
    cf.destroy();
}