@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)); }
/** * Determine the specific executor to use when executing the given method. * @return the executor to use (or {@code null}, but just if no default executor has been set) */ protected AsyncTaskExecutor determineAsyncExecutor(Method method) { AsyncTaskExecutor executor = this.executors.get(method); if (executor == null) { Executor executorToUse = this.defaultExecutor; String qualifier = getExecutorQualifier(method); if (StringUtils.hasLength(qualifier)) { Assert.notNull(this.beanFactory, "BeanFactory must be set on " + getClass().getSimpleName() + " to access qualified executor '" + qualifier + "'"); executorToUse = BeanFactoryAnnotationUtils.qualifiedBeanOfType( this.beanFactory, Executor.class, qualifier); } else if (executorToUse == null) { return null; } executor = (executorToUse instanceof AsyncTaskExecutor ? (AsyncTaskExecutor) executorToUse : new TaskExecutorAdapter(executorToUse)); this.executors.put(method, executor); } return executor; }
/** * Determine the specific executor to use when executing the given method. * Should preferably return an {@link AsyncListenableTaskExecutor} implementation. * @return the executor to use (or {@code null}, but just if no default executor has been set) */ protected AsyncTaskExecutor determineAsyncExecutor(Method method) { AsyncTaskExecutor executor = this.executors.get(method); if (executor == null) { Executor executorToUse = this.defaultExecutor; String qualifier = getExecutorQualifier(method); if (StringUtils.hasLength(qualifier)) { if (this.beanFactory == null) { throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() + " to access qualified executor '" + qualifier + "'"); } executorToUse = BeanFactoryAnnotationUtils.qualifiedBeanOfType( this.beanFactory, Executor.class, qualifier); } else if (executorToUse == null) { return null; } executor = (executorToUse instanceof AsyncListenableTaskExecutor ? (AsyncListenableTaskExecutor) executorToUse : new TaskExecutorAdapter(executorToUse)); this.executors.put(method, executor); } return executor; }
/** * Delegate for actually executing the given task with the chosen executor. * @param task the task to execute * @param executor the chosen executor * @param returnType the declared return type (potentially a {@link Future} variant) * @return the execution result (potentially a corresponding {@link Future} handle) */ protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) { if (completableFuturePresent) { Future<Object> result = CompletableFutureDelegate.processCompletableFuture(returnType, task, executor); if (result != null) { return result; } } if (ListenableFuture.class.isAssignableFrom(returnType)) { return ((AsyncListenableTaskExecutor) executor).submitListenable(task); } else if (Future.class.isAssignableFrom(returnType)) { return executor.submit(task); } else { executor.submit(task); return null; } }
@Test public void startCallableProcessingWithAsyncTask() throws Exception { AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class); given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest); @SuppressWarnings("unchecked") WebAsyncTask<Object> asyncTask = new WebAsyncTask<Object>(1000L, executor, mock(Callable.class)); this.asyncManager.startCallableProcessing(asyncTask); verify(executor).submit((Runnable) notNull()); verify(this.asyncWebRequest).setTimeout(1000L); verify(this.asyncWebRequest).addTimeoutHandler(any(Runnable.class)); verify(this.asyncWebRequest).addCompletionHandler(any(Runnable.class)); verify(this.asyncWebRequest).startAsync(); }
/** * 根据文件访问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; }
/** * Crea un nuevo executor. Véase {@link #getAsyncExecutor()} * * @return {@link Executor} de tareas asíncronas * @see <a href="http://appcia.cnc.una.py/wf/index.php/Asyn_task">Wiki</a> */ @Bean public AsyncTaskExecutor asyncExecutor() { final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize( getInt("karaku.async.pool.size", DEFAULT_CORE_POOL_SIZE)); executor.setMaxPoolSize(getInt("karaku.async.pool.max_size", DEFAULT_CORE_POOL_MAX_SIZE)); executor.setQueueCapacity( getInt("karaku.async.queue.size", DEFAULT_ASYNC_QUEUE_SIZE)); executor.setThreadNamePrefix(properties .get("karaku.async.thread.prefix", DEFAULT_THREAD_PREFIX)); // TODO cambiar por un SyncTaskExecutor return executor; }
/** * Create a default TaskExecutor. Called if no explicit TaskExecutor has been specified. * <p>The default implementation builds a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} * with the specified bean name (or the class name, if no bean name specified) as thread name prefix. * * @return a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} configured with the thread name prefix * @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String) */ protected AsyncTaskExecutor createDefaultTaskExecutor() { String beanName = getBeanName(); ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setThreadNamePrefix(beanName != null ? beanName + "-" : DEFAULT_THREAD_NAME_PREFIX); int spinningThreads = this.getRegisteredQueues().size(); if (spinningThreads > 0) { threadPoolTaskExecutor.setCorePoolSize(spinningThreads * DEFAULT_WORKER_THREADS); int maxNumberOfMessagePerBatch = getMaxNumberOfMessages() != null ? getMaxNumberOfMessages() : DEFAULT_WORKER_THREADS; threadPoolTaskExecutor.setMaxPoolSize(spinningThreads * (maxNumberOfMessagePerBatch + 1)); } // No use of a thread pool executor queue to avoid retaining message to long in memory threadPoolTaskExecutor.setQueueCapacity(0); threadPoolTaskExecutor.afterPropertiesSet(); return threadPoolTaskExecutor; }
private void listenForAnswersOf( LifxMessage messageSent, LifxMessageType expectedResponseType, CompletableFuture<LifxMessage[]> results) { this.clientsWaiting.put(expectedResponseType, results); if (this.listening) return; this.listening = true; log.debug("|-- Going to start listen task.."); if(this.listenerExecutor instanceof AsyncTaskExecutor){ ((AsyncTaskExecutor)this.listenerExecutor).execute( new UdpListenExcecutor(clientsWaiting), AsyncTaskExecutor.TIMEOUT_IMMEDIATE ); }else{ this.listenerExecutor.execute(new UdpListenExcecutor(clientsWaiting)); } }
private WebAsyncTask(Long timeout, AsyncTaskExecutor executor, String executorName, Callable<V> callable) { Assert.notNull(callable, "Callable must not be null"); this.callable = callable; this.timeout = timeout; this.executor = executor; this.executorName = executorName; }
/** * Return the AsyncTaskExecutor to use for concurrent handling, or {@code null}. */ public AsyncTaskExecutor getExecutor() { if (this.executor != null) { return this.executor; } else if (this.executorName != null) { Assert.state(this.beanFactory != null, "A BeanFactory is required to look up a task executor bean"); return this.beanFactory.getBean(this.executorName, AsyncTaskExecutor.class); } else { return null; } }
/** * Get a task executor for executing tasks asynchronously that don't need to be scheduled at a recurring rate. * * @param registry registry for spectator * @param metacatProperties The metacat properties to get number of executor threads from. * Likely best to do one more than number of CPUs * @return The task executor the system to use */ @Bean public AsyncTaskExecutor taskExecutor(final Registry registry, final MetacatProperties metacatProperties) { final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(metacatProperties.getEvent().getBus().getExecutor().getThread().getCount()); executor.initialize(); RegistryUtil.registerThreadPool(registry, "metacat.event.pool", executor.getThreadPoolExecutor()); return executor; }
/** * Create a {@code WebAsyncTask} with a timeout value, an executor instance, and a Callable. * @param timeout timeout value in milliseconds; ignored if {@code null} * @param executor the executor to use * @param callable the callable for concurrent handling */ public WebAsyncTask(Long timeout, AsyncTaskExecutor executor, Callable<V> callable) { this(callable); Assert.notNull(executor, "Executor must not be null"); this.executor = executor; this.timeout = timeout; }
/** * Return the AsyncTaskExecutor to use for concurrent handling, * or {@code null} if none specified. */ public AsyncTaskExecutor getExecutor() { if (this.executor != null) { return this.executor; } else if (this.executorName != null) { Assert.state(this.beanFactory != null, "BeanFactory is required to look up an executor bean by name"); return this.beanFactory.getBean(this.executorName, AsyncTaskExecutor.class); } else { return null; } }
@Before public void setUp() { this.servletRequest = new MockHttpServletRequest("GET", "/test"); this.servletRequest.setAsyncSupported(true); this.servletResponse = new MockHttpServletResponse(); this.asyncWebRequest = new StandardServletAsyncWebRequest(servletRequest, servletResponse); AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class); this.asyncManager = WebAsyncUtils.getAsyncManager(servletRequest); this.asyncManager.setTaskExecutor(executor); this.asyncManager.setAsyncWebRequest(this.asyncWebRequest); }
@Bean public AsyncTaskExecutor asyncTaskExecutor(@Value("${async.threadpool.coresize:16}") int corePoolSize, @Value("${async.threadpool.maxsize:64}") int maxPoolSize, @Value("${async.threadpool.capacity:1024}") int queueCapacity) { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(corePoolSize); taskExecutor.setMaxPoolSize(maxPoolSize); taskExecutor.setQueueCapacity(queueCapacity); taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); taskExecutor.setWaitForTasksToCompleteOnShutdown(true); taskExecutor.afterPropertiesSet(); return taskExecutor; }
@Bean public WebMvcConfigurerAdapter webMvcConfigurerAdapter(AsyncTaskExecutor asyncTaskExecutor) { return new WebMvcConfigurerAdapter() { @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { configurer.setTaskExecutor(asyncTaskExecutor); super.configureAsyncSupport(configurer); } }; }
@Bean @Qualifier("pollableTaskExecutor") public AsyncTaskExecutor getPollableTaskExecutor() { ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setBeanName("pollableTask"); threadPoolTaskExecutor.setCorePoolSize(5); threadPoolTaskExecutor.setMaxPoolSize(10); threadPoolTaskExecutor.initialize(); return new DelegatingSecurityContextAsyncTaskExecutor(threadPoolTaskExecutor); }
/** * Determine the specific executor to use when executing the given method. * Should preferably return an {@link AsyncListenableTaskExecutor} implementation. * @return the executor to use (or {@code null}, but just if no default executor is available) */ protected AsyncTaskExecutor determineAsyncExecutor(Method method) { AsyncTaskExecutor executor = this.executors.get(method); if (executor == null) { Executor targetExecutor; String qualifier = getExecutorQualifier(method); if (StringUtils.hasLength(qualifier)) { targetExecutor = findQualifiedExecutor(this.beanFactory, qualifier); } else { targetExecutor = this.defaultExecutor; if (targetExecutor == null) { synchronized (this.executors) { if (this.defaultExecutor == null) { this.defaultExecutor = getDefaultExecutor(this.beanFactory); } targetExecutor = this.defaultExecutor; } } } if (targetExecutor == null) { return null; } executor = (targetExecutor instanceof AsyncListenableTaskExecutor ? (AsyncListenableTaskExecutor) targetExecutor : new TaskExecutorAdapter(targetExecutor)); this.executors.put(method, executor); } return executor; }
public BootstrapSessionFactoryInvocationHandler(AsyncTaskExecutor bootstrapExecutor) { this.sessionFactoryFuture = bootstrapExecutor.submit(new Callable<SessionFactory>() { @Override public SessionFactory call() throws Exception { return buildSessionFactory(); } }); }
@Bean public AsyncTaskExecutor sqsPollerExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(SQS_POLLER_THREAD_POOL_SIZE); executor.setThreadNamePrefix(SQS_POLLER_THREAD_NAME_PREFIX); executor.setWaitForTasksToCompleteOnShutdown(false); executor.initialize(); return new ConcurrentTaskExecutor(executor); }
public AsyncWebProcessor<?> build(){ if(asyncTaskExecutor==null){ asyncTaskExecutor = Springs.getInstance().getBean(AsyncTaskExecutor.class); } if(StringUtils.isBlank(asynCallback)){ asynCallback = AsyncUtils.getAsyncCallbackName(DEFAULT_ASYNCALLBACK); } response.setContentType(contentType); DefaultAsyncWebProcessor<?> processor = null; try { if(progressProcessor){ if(messageTunnel==null){ messageTunnel = new StringMessageHolder(); } processor = new DefaultProgressAsyncWebProcessor(response.getWriter(), (AsyncMessageHolder)messageTunnel, asyncTaskExecutor); }else{ if(messageTunnel==null){ messageTunnel = new StringMessageTunnel(); } processor = new DefaultAsyncWebProcessor<>(response.getWriter(), messageTunnel, asyncTaskExecutor); } processor.setSleepTime(flushInSecond); processor.setAsynCallback(asynCallback); } catch (IOException e) { throw new BaseException("build processor error: " + e.getMessage()); } return processor; }
public DefaultAsyncWebProcessor(PrintWriter out, AsyncMessageTunnel<MSG> holder, AsyncTaskExecutor asyncTaskExecutor) { super(); this.out = out; // this.dataCountPerTask = taskInterval; this.asynMessageTunnel = holder; Assert.notNull(asyncTaskExecutor, "no asyncTaskExecutor found, please add a asyncTaskExecutor to spring context!"); this.asyncTaskExecutor = asyncTaskExecutor; }
@Bean(MVC_ASYNC_TASK_BEAN_NAME) @ConditionalOnMissingBean(name=AsyncMvcConfiguration.MVC_ASYNC_TASK_BEAN_NAME) public AsyncTaskExecutor mvcAsyncTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(mvcAsyncProperties.getCorePoolSize()); executor.setMaxPoolSize(mvcAsyncProperties.getMaxPoolSize()); executor.setQueueCapacity(mvcAsyncProperties.getQueueCapacity()); return executor; }
@Bean(ASYNC_TASK_BEAN_NAME) @ConditionalOnMissingBean(name=AsyncTaskConfiguration.ASYNC_TASK_BEAN_NAME) public AsyncTaskExecutor mvcAsyncTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(asyncTaskProperties.getCorePoolSize()); executor.setMaxPoolSize(asyncTaskProperties.getMaxPoolSize()); executor.setQueueCapacity(asyncTaskProperties.getQueueCapacity()); return executor; }
/** * Constructor for use by tests */ ImportJob(AsyncTaskExecutor executor, ImportHandlerCallablesFactory callablesFactory, Semaphore gate, InternalRepositoryService repositoryService) { parallelImportsGate = gate; this.callablesFactory = callablesFactory; this.taskExecutor = executor; this.repositoryService = repositoryService; }
@Bean public AsyncTaskExecutor taskExecutorSmtp(){ ThreadPoolTaskExecutor res = new ThreadPoolTaskExecutor(); res.setCorePoolSize(corePoolsize); res.setMaxPoolSize(maxPoolsize); res.setQueueCapacity(queueCapacity); res.setKeepAliveSeconds(keepAliveSeconds); res.setThreadNamePrefix("crowd-smtp-"); return res; }
public <P, I> List<I> runSimulation(Simulation<P, I> simulation, P fields, AsyncTaskExecutor taskExecutor) { Assert.notNull(simulation); Assert.notNull(fields); simulation.setTaskExecutor(taskExecutor); simulation.setFields(fields); List<I> outputs = simulation.call(); return outputs; }
private AsyncTaskExecutor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("asyncExecutor-"); executor.initialize(); return executor; }
@Bean(name="hapiJpaTaskExecutor") public AsyncTaskExecutor taskScheduler() { ConcurrentTaskScheduler retVal = new ConcurrentTaskScheduler(); retVal.setConcurrentExecutor(scheduledExecutorService().getObject()); retVal.setScheduledExecutor(scheduledExecutorService().getObject()); return retVal; }
/** * Constructor */ public SubscriptionActivatingSubscriber(IFhirResourceDao<? extends IBaseResource> theSubscriptionDao, Subscription.SubscriptionChannelType theChannelType, BaseSubscriptionInterceptor theSubscriptionInterceptor, PlatformTransactionManager theTransactionManager, AsyncTaskExecutor theTaskExecutor) { mySubscriptionDao = theSubscriptionDao; mySubscriptionInterceptor = theSubscriptionInterceptor; myChannelType = theChannelType; myCtx = theSubscriptionDao.getContext(); myTransactionManager = theTransactionManager; myTaskExecutor = theTaskExecutor; Validate.notNull(theTaskExecutor); }
@Override public RequestMappingHandlerAdapter doWith(RequestMappingHandlerAdapter handlerAdapter, String beanName, ApplicationContext applicationContext) { final AsyncTaskExecutor executor = (AsyncTaskExecutor) applicationContext.getBean(EXECUTOR); handlerAdapter.setTaskExecutor(executor); return handlerAdapter; }
@Bean public AsyncTaskExecutor taskExecutor() { ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(10); threadPoolTaskExecutor.setMaxPoolSize(200); threadPoolTaskExecutor.setQueueCapacity(0); threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return threadPoolTaskExecutor; }