Java 类org.springframework.core.task.SimpleAsyncTaskExecutor 实例源码

项目:simbest-cores    文件:AppFileUtils.java   
/**
 * 根据文件访问URL列表, 将文件从云存储或应用系统Context路径下的文件删除
 * <p>
 * 调用带有返回值的多线程(实现callable接口),也是同步的。参考:http://blueram.iteye.com/blog/1583117
 *
 * @param fileUrls
 * @return 返回存储路径
 */
public Integer deleteFiles(Collection<String> fileUrls) {
    int count = 0;
    AsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
    for (String url : fileUrls) {
        final String fileUrl = StringUtils.substringAfterLast(url, coreConfig.getValue("bae.bcs.bucket") + "/");
        try {
            Future<Integer> future = executor.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    deleteFile(fileUrl);
                    return 1;
                }
            });
            count += future.get();
        } catch (InterruptedException | ExecutionException e) {
            Exceptions.printException(e);
        }
    }
    return count;
}
项目:commercetools-sunrise-data    文件:SuggestKeywordsFromNameJobConfiguration.java   
@Bean
    public TaskExecutor taskExecutor() {
        //https://jira.spring.io/browse/BATCH-2269
        final SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor() {
            @Override
            protected void doExecute(Runnable task) {
                //gets the jobExecution of the configuration thread
                final JobExecution jobExecution = JobSynchronizationManager.getContext().getJobExecution();
                super.doExecute(() -> {
                    JobSynchronizationManager.register(jobExecution);
                    try {
                        task.run();
                    } finally {
//                        JobSynchronizationManager.release();
                        JobSynchronizationManager.close();
                    }
                });
            }
        };
        simpleAsyncTaskExecutor.setConcurrencyLimit(20);
        return simpleAsyncTaskExecutor;
    }
项目:booties    文件:AsyncExecutorConfiguration.java   
@Override
public Executor getAsyncExecutor() {
    if (properties.isEnabled()) {
        ThreadPoolTaskExecutor executor = null;
        try {
            executor = beanFactory.getBean(ThreadPoolTaskExecutor.class);
        } catch (NoUniqueBeanDefinitionException e) {
            executor = beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, ThreadPoolTaskExecutor.class);
        } catch (NoSuchBeanDefinitionException ex) {
        }
        if (executor != null) {
            log.info("use default TaskExecutor ...");
            return executor;
        } else {
            throw new BeanCreationException("Expecting a 'ThreadPoolTaskExecutor' exists, but was 'null'");
        }
    } else {
        log.info(
                "'AsyncExecutorConfiguration' is disabled, so create 'SimpleAsyncTaskExecutor' with 'threadNamePrefix' - '{}'",
                properties.getThreadNamePrefix());
        return new SimpleAsyncTaskExecutor(properties.getThreadNamePrefix());
    }
}
项目:bulbs-core    文件:BulbsHwServiceImplTest.java   
@Before
public void setUp() {
    ReflectionTestUtils.setField(
            instance2Test, 
            "hwAdapter_Rest", 
            mk_hwAdapter); 

    //~ INIT ONCE ~~~~~~~~~~~~~~
    if(initialized)return ;
    initialized = true;
    ReflectionTestUtils.setField(
            instance2Test, 
            "asyncExecutor", 
            new SimpleAsyncTaskExecutor("testBulbsHwService_")); 

    ReflectionTestUtils.setField(new BulbsCoreEventProcessor(), "eventStore", 
            mk_eventStore);
    serviceLocator = new DomainServiceLocator();
    ReflectionTestUtils.setField(serviceLocator, "instance", mk_domainServiceLocator);
}
项目:hub-fortify-ssc-integration-service    文件:SpringConfiguration.java   
/**
 * Create the task executor which will be used for multi-threading
 *
 * @return TaskExecutor
 */
@Bean
public TaskExecutor taskExecutor() {
    SimpleAsyncTaskExecutor asyncTaskExecutor = new SimpleAsyncTaskExecutor("spring_batch");
    asyncTaskExecutor.setConcurrencyLimit(SimpleAsyncTaskExecutor.NO_CONCURRENCY);
    return asyncTaskExecutor;
}
项目:spring4-understanding    文件:StandardWebSocketClientTests.java   
@Test
public void taskExecutor() throws Exception {

    URI uri = new URI("ws://localhost/abc");
    this.wsClient.setTaskExecutor(new SimpleAsyncTaskExecutor());
    WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

    assertNotNull(session);
}
项目:spring4-understanding    文件:JettyWebSocketClientTests.java   
@Test
public void doHandshakeWithTaskExecutor() throws Exception {

    WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
    headers.setSecWebSocketProtocol(Arrays.asList("echo"));

    this.client.setTaskExecutor(new SimpleAsyncTaskExecutor());
    this.wsSession = this.client.doHandshake(new TextWebSocketHandler(), headers, new URI(this.wsUrl)).get();

    assertEquals(this.wsUrl, this.wsSession.getUri().toString());
    assertEquals("echo", this.wsSession.getAcceptedProtocol());
}
项目:spring4-understanding    文件:BufferedSimpleAsyncHttpRequestFactoryTests.java   
@Override
protected AsyncClientHttpRequestFactory createRequestFactory() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    AsyncListenableTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    requestFactory.setTaskExecutor(taskExecutor);
    return requestFactory;
}
项目:TaskMadness    文件:JobConfiguration.java   
@Bean
public Step step1() {
    return stepBuilderFactory.get("step1")
            .<Bracket, Bracket>chunk(10000)
            .reader(itemReader())
            .processor(itemProcessor())
            .writer(itemWriter(null))
            .taskExecutor(new SimpleAsyncTaskExecutor())
            .build();
}
项目:jhipster    文件:AsyncSpringLiquibaseTest.java   
@Before
public void setup() {
    executor = new SimpleAsyncTaskExecutor();
    recorder = LogbackRecorder.forClass(MockEnvironment.class).reset().capture("ALL");
    environment = new MockEnvironment();
    recorder.release();
    config = spy(new TestAsyncSpringLiquibase(executor, environment));
    recorder = LogbackRecorder.forClass(AsyncSpringLiquibase.class).reset().capture("ALL");
}
项目:signature-processing    文件:BatchConfig.java   
/**
 * @return task executor
 *
 * @see https://jira.spring.io/browse/BATCH-2269
 */
@Bean
public TaskExecutor taskExecutor() {
    return new SimpleAsyncTaskExecutor() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void doExecute(Runnable task) {

            /* Gets the jobExecution of the configuration thread */
            JobExecution jobExecution = JobSynchronizationManager
                    .getContext()
                    .getJobExecution();

            super.doExecute(new Runnable() {
                @Override
                public void run() {
                    JobSynchronizationManager.register(jobExecution);

                    try {
                        task.run();
                    } finally {
                        JobSynchronizationManager.release();
                    }
                }
            });
        }
    };
}
项目:xap-openspaces    文件:TaskExecutorEventListenerAdapter.java   
/**
 * Initializes the task executor adapter. Expects the delegate to be set. If no
 * {@link #setTaskExecutor(org.springframework.core.task.TaskExecutor) taskExecutor} is
 * provided will create a default one using {@link org.springframework.core.task.SimpleAsyncTaskExecutor}. 
 */
public void afterPropertiesSet() throws Exception {
    Assert.notNull(delegate, "delegate SpaceDataEventListener must not be null");
    if (taskExecutor == null) {
        SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();
        simpleAsyncTaskExecutor.setDaemon(true);
        taskExecutor = simpleAsyncTaskExecutor;
    }
}
项目:burstcoin-jminer    文件:CoreConfig.java   
@Bean(name = "networkPool")
public SimpleAsyncTaskExecutor networkPool()
{
  SimpleAsyncTaskExecutor pool = new SimpleAsyncTaskExecutor();
  pool.setThreadPriority(Thread.NORM_PRIORITY + 1);
  return pool;
}
项目:router-metrics-provider    文件:GatheringConfig.java   
private AsyncRestTemplate getAsyncRestTemplate() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setTaskExecutor(new SimpleAsyncTaskExecutor());
    factory.setConnectTimeout(gorouterProperties.getConnectTimeout());
    factory.setReadTimeout(gorouterProperties.getReadTimeout());

    return new AsyncRestTemplate(factory);
}
项目:data-prep    文件:CSVSerializerTest.java   
public CSVSerializerTest() {
    this.serializer = new CSVSerializer();
    TaskExecutor executor = new SimpleAsyncTaskExecutor();
    ReflectionTestUtils.setField(serializer, "executor", executor);
    ReflectionTestUtils.setField(serializer, "defaultTextEnclosure", "\"");
    ReflectionTestUtils.setField(serializer, "defaultEscapeChar", "\u0000");

}
项目:spring-cloud-aws    文件:SimpleMessageListenerContainerTest.java   
@Test
public void testCustomTaskExecutor() throws Exception {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    container.setTaskExecutor(taskExecutor);

    container.setAmazonSqs(mock(AmazonSQSAsync.class, withSettings().stubOnly()));
    container.setMessageHandler(mock(QueueMessageHandler.class));
    container.setBeanName("testContainerName");
    container.afterPropertiesSet();

    assertEquals(taskExecutor, container.getTaskExecutor());
}
项目:spring-cloud-aws    文件:SimpleMessageListenerContainerTest.java   
@Test
public void testContainerDoesNotProcessMessageAfterBeingStopped() throws Exception {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    container.setTaskExecutor(taskExecutor);

    AmazonSQSAsync sqs = mock(AmazonSQSAsync.class, withSettings().stubOnly());
    container.setAmazonSqs(sqs);

    QueueMessageHandler messageHandler = new QueueMessageHandler() {

        @Override
        public void handleMessage(org.springframework.messaging.Message<?> message) throws MessagingException {
            fail("Should not have been called");
        }
    };
    container.setMessageHandler(messageHandler);
    container.setBeanName("testContainerName");

    mockGetQueueUrl(sqs, "testQueue", "http://testContainerDoesNotProcessMessageAfterBeingStopped.amazonaws.com");

    container.afterPropertiesSet();

    when(sqs.receiveMessage(new ReceiveMessageRequest("http://testContainerDoesNotProcessMessageAfterBeingStopped.amazonaws.com"))).
            thenAnswer((Answer<ReceiveMessageResult>) invocation -> {
                container.stop();
                return new ReceiveMessageResult().withMessages(new Message().withBody("test"));
            });

    container.start();
}
项目:saos    文件:BatchCoreConfiguration.java   
/** job launcher used for executing jobs on http requests, here: for batch admin */
@Bean 
public JobLauncher asyncJobLauncher() throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository());
    jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
    jobLauncher.afterPropertiesSet();
    return jobLauncher;
}
项目:spring-osgi    文件:ExtenderConfiguration.java   
/**
 * {@inheritDoc}
 * 
 * Cleanup the configuration items.
 */
public void destroy() {

    synchronized (lock) {
        if (isMulticasterManagedInternally) {
            eventMulticaster.removeAllListeners();
            eventMulticaster = null;
        }

        if (extenderConfiguration != null) {
            extenderConfiguration.close();
            extenderConfiguration = null;
        }

        // postpone the task executor shutdown
        if (forceThreadShutdown) {

            if (isTaskExecutorManagedInternally) {
                log.warn("Forcing the (internally created) taskExecutor to stop...");
                ThreadGroup th = ((SimpleAsyncTaskExecutor) taskExecutor).getThreadGroup();
                if (!th.isDestroyed()) {
                    // ask the threads nicely to stop
                    th.interrupt();
                }
            }
            taskExecutor = null;
        }

        if (isShutdownTaskExecutorManagedInternally) {
            try {
                ((DisposableBean) shutdownTaskExecutor).destroy();
            }
            catch (Exception ex) {
                log.debug("Received exception while shutting down shutdown task executor", ex);
            }
            shutdownTaskExecutor = null;
        }
    }
}
项目:spring-osgi    文件:ExtenderConfiguration.java   
private TaskExecutor createDefaultTaskExecutor() {
    // create thread-pool for starting contexts
    ThreadGroup threadGroup = new ThreadGroup("spring-osgi-extender[" + ObjectUtils.getIdentityHexString(this)
            + "]-threads");
    threadGroup.setDaemon(false);

    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    taskExecutor.setThreadGroup(threadGroup);
    taskExecutor.setThreadNamePrefix("SpringOsgiExtenderThread-");

    isTaskExecutorManagedInternally = true;

    return taskExecutor;
}
项目:spring4-sandbox    文件:JpaBatchConfigurer.java   
private JobLauncher createJobLauncher() throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    jobLauncher.setTaskExecutor( new SimpleAsyncTaskExecutor());
    jobLauncher.afterPropertiesSet();
    return jobLauncher;
}
项目:lams    文件:AsyncAnnotationAdvisor.java   
/**
 * Create a new {@code AsyncAnnotationAdvisor} for bean-style configuration.
 */
public AsyncAnnotationAdvisor() {
    this(new SimpleAsyncTaskExecutor());
}
项目:java-spring-cloud    文件:DefaultAsyncAutoConfiguration.java   
@Override
public Executor getAsyncExecutor() {
  return new TracedExecutor(new SimpleAsyncTaskExecutor(), tracer);
}
项目:java-spring-cloud    文件:TracedExecutorTest.java   
@Bean
public Executor simpleAsyncTaskExecutor() {
  return new SimpleAsyncTaskExecutor();
}
项目:item-shop-reactive-backend    文件:Server.java   
@Bean(name="taskScheduler")
public Executor taskScheduler() {
    return new SimpleAsyncTaskExecutor();
}
项目:cqrs-es-kafka    文件:CommandMessagingConfigurer.java   
@Bean
public TaskExecutor consumerTaskExecutor() {
    return new SimpleAsyncTaskExecutor();
}
项目:cqrs-es-kafka    文件:EventMessagingConfigurer.java   
@Bean
public TaskExecutor consumerTaskExecutor() {
    return new SimpleAsyncTaskExecutor();
}
项目:message-gateway    文件:MessageGatewayConfiguration.java   
@Bean
public SimpleApplicationEventMulticaster applicationEventMulticaster() {
    final SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
    multicaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
    return multicaster;
}
项目:java-remote-partitioning    文件:JobConfiguration.java   
@Bean
public ExecutorChannel outboundRequests() {
    return MessageChannels.executor("outboundRequests", new SimpleAsyncTaskExecutor()).get();
}
项目:my-spring-cache-redis    文件:AsyncAnnotationAdvisor.java   
/**
 * Create a new {@code AsyncAnnotationAdvisor} for bean-style configuration.
 */
public AsyncAnnotationAdvisor() {
    this(new SimpleAsyncTaskExecutor());
}
项目:java-restify    文件:RestifyAsyncConfiguration.java   
@Conditional(RestifyAsyncConfiguration.RestifyAsyncTaskExecutorCondition.class)
@Bean
public AsyncListenableTaskExecutor restifyAsyncTaskExecutor() {
    return new SimpleAsyncTaskExecutor("RestifyAsyncTaskExecutor");
}
项目:java-restify    文件:WebAsyncTaskEndpointCallExecutableFactory.java   
public WebAsyncTaskEndpointCallExecutableFactory() {
    this(new SimpleAsyncTaskExecutor());
}
项目:java-restify    文件:WebAsyncTaskEndpointCallExecutableFactory.java   
public WebAsyncTaskEndpointCallExecutableFactory(Long timeout) {
    this(timeout, new SimpleAsyncTaskExecutor());
}
项目:java-restify    文件:ListenableFutureTaskEndpointCallExecutableFactory.java   
public ListenableFutureTaskEndpointCallExecutableFactory() {
    this(new SimpleAsyncTaskExecutor());
}
项目:java-restify    文件:ListenableFutureEndpointCallExecutableFactory.java   
public ListenableFutureEndpointCallExecutableFactory() {
    this(new SimpleAsyncTaskExecutor("ListenableFutureEndpointCallExecutable"));
}
项目:flowable-examples    文件:ProcessApplication.java   
@Bean
public TaskExecutor taskExecutor() {
    return new SimpleAsyncTaskExecutor();
}
项目:Catdogtion    文件:CatdogtionApplication.java   
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
  SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
  eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
  return eventMulticaster;
}
项目:burstcoin-observer    文件:Observer.java   
@Bean(name = "networkTaskExecutor")
public SimpleAsyncTaskExecutor roundPool()
{
  SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
  return taskExecutor;
}
项目:spring-cloud-stream-binder-rabbit    文件:RabbitMessageChannelBinder.java   
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination consumerDestination, String group,
        ExtendedConsumerProperties<RabbitConsumerProperties> properties) {
    Assert.state(!HeaderMode.embeddedHeaders.equals(properties.getHeaderMode()),
            "the RabbitMQ binder does not support embedded headers since RabbitMQ supports headers natively");
    String destination = consumerDestination.getName();
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    listenerContainer.setAcknowledgeMode(properties.getExtension().getAcknowledgeMode());
    listenerContainer.setChannelTransacted(properties.getExtension().isTransacted());
    listenerContainer.setDefaultRequeueRejected(properties.getExtension().isRequeueRejected());
    int concurrency = properties.getConcurrency();
    concurrency = concurrency > 0 ? concurrency : 1;
    listenerContainer.setConcurrentConsumers(concurrency);
    int maxConcurrency = properties.getExtension().getMaxConcurrency();
    if (maxConcurrency > concurrency) {
        listenerContainer.setMaxConcurrentConsumers(maxConcurrency);
    }
    listenerContainer.setPrefetchCount(properties.getExtension().getPrefetch());
    listenerContainer.setRecoveryInterval(properties.getExtension().getRecoveryInterval());
    listenerContainer.setTxSize(properties.getExtension().getTxSize());
    listenerContainer.setTaskExecutor(new SimpleAsyncTaskExecutor(consumerDestination.getName() + "-"));
    listenerContainer.setQueueNames(consumerDestination.getName());
    listenerContainer.setAfterReceivePostProcessors(this.decompressingPostProcessor);
    listenerContainer.setMessagePropertiesConverter(
            RabbitMessageChannelBinder.inboundMessagePropertiesConverter);
    listenerContainer.setExclusive(properties.getExtension().isExclusive());
    listenerContainer.setMissingQueuesFatal(properties.getExtension().getMissingQueuesFatal());
    if (properties.getExtension().getQueueDeclarationRetries() != null) {
        listenerContainer.setDeclarationRetries(properties.getExtension().getQueueDeclarationRetries());
    }
    if (properties.getExtension().getFailedDeclarationRetryInterval() != null) {
        listenerContainer.setFailedDeclarationRetryInterval(
                properties.getExtension().getFailedDeclarationRetryInterval());
    }
    listenerContainer.afterPropertiesSet();

    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    adapter.setBeanFactory(this.getBeanFactory());
    adapter.setBeanName("inbound." + destination);
    DefaultAmqpHeaderMapper mapper = DefaultAmqpHeaderMapper.inboundMapper();
    mapper.setRequestHeaderNames(properties.getExtension().getHeaderPatterns());
    adapter.setHeaderMapper(mapper);
    ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(consumerDestination, group, properties);
    if (properties.getMaxAttempts() > 1) {
        adapter.setRetryTemplate(buildRetryTemplate(properties));
        if (properties.getExtension().isRepublishToDlq()) {
            adapter.setRecoveryCallback(errorInfrastructure.getRecoverer());
        }
    }
    else {
        adapter.setErrorMessageStrategy(errorMessageStrategy);
        adapter.setErrorChannel(errorInfrastructure.getErrorChannel());
    }
    return adapter;
}
项目:wonderjameeee    文件:WebConfig.java   
@Bean
public AsyncTaskExecutor asyncTaskExecutor() {
    return new SimpleAsyncTaskExecutor("async");
}