org.apache.commons.lang3.concurrent.BasicThreadFactory Java Examples

The following examples show how to use org.apache.commons.lang3.concurrent.BasicThreadFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultAsyncJobExecutor.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void initAsyncJobExecutionThreadPool() {
    if (threadPoolQueue == null) {
        LOGGER.info("Creating thread pool queue of size {}", queueSize);
        threadPoolQueue = new ArrayBlockingQueue<>(queueSize);
    }

    if (executorService == null) {
        LOGGER.info("Creating executor service with corePoolSize {}, maxPoolSize {} and keepAliveTime {}", corePoolSize, maxPoolSize, keepAliveTime);

        BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern(threadPoolNamingPattern).build();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
            TimeUnit.MILLISECONDS, threadPoolQueue, threadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(allowCoreThreadTimeout);
        executorService = threadPoolExecutor;
    }
}
 
Example #2
Source File: TwitchClient.java    From twitch4j with MIT License 6 votes vote down vote up
/**
 * Close
 */
public void close() {
    log.info("Closing TwitchClient ...");

    // Modules
    if (this.chat != null) {
        this.chat.close();
    }
    if (this.pubsub != null) {
        this.pubsub.close();
    }
    if (this.twitchClientHelper != null) {
        twitchClientHelper.close();
    }

    // Shutdown ThreadPools created by Twitch4J
    if (scheduledThreadPoolExecutor.getThreadFactory() instanceof BasicThreadFactory) {
        BasicThreadFactory threadFactory = (BasicThreadFactory) scheduledThreadPoolExecutor.getThreadFactory();

        if (threadFactory.getNamingPattern().equalsIgnoreCase("twitch4j-%d")) {
            scheduledThreadPoolExecutor.shutdownNow();
        }
    }
}
 
Example #3
Source File: NodeServerInfoWatchdog.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
@PostConstruct
    public void init() {

        scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("SendNodeServerInfo-schedule-pool-%d").daemon(true).build());
        scheduledExecutorService.scheduleAtFixedRate(() ->
                {
                    //将负载加载到ZK中
                    if (!CollectionUtils.isEmpty(dataCenterChannelStore.getAllChannels())) {
                        dataCenterChannelStore.getAllChannels().stream().forEach(e -> {
                            log.info("channel id:{}, {}", e.id(), e);
                        });
                    }
                    applicationEventPublisher.publishEvent(
                            NodeServerInfoEvent.builder()
                                    .name(goPushNodeServerConfig.getName())
                                    .nodeServerInfo(watch())
                                    .build());
//                写入zk 其实不需要发送 NodeInfoReq
                    nodeSender.send(NodeInfoReq.builder().build());
                }
                , delay, delay, TimeUnit.MILLISECONDS);

    }
 
Example #4
Source File: TaskPollExecutor.java    From conductor with Apache License 2.0 6 votes vote down vote up
TaskPollExecutor(EurekaClient eurekaClient, TaskClient taskClient, int threadCount, int updateRetryCount,
    String workerNamePrefix) {
    this.eurekaClient = eurekaClient;
    this.taskClient = taskClient;
    this.updateRetryCount = updateRetryCount;

    LOGGER.info("Initialized the TaskPollExecutor with {} threads", threadCount);

    AtomicInteger count = new AtomicInteger(0);

    this.executorService = Executors.newFixedThreadPool(threadCount,
        new BasicThreadFactory.Builder()
            .namingPattern(workerNamePrefix + count.getAndIncrement())
            .uncaughtExceptionHandler(uncaughtExceptionHandler)
            .build());

    this.pollingSemaphore = new PollingSemaphore(threadCount);
}
 
Example #5
Source File: Executor.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
@Inject
private Executor(@Parameter(JobConf.ExecutorId.class) final String executorId,
                 final PersistentConnectionToMasterMap persistentConnectionToMasterMap,
                 final MessageEnvironment messageEnvironment,
                 final SerializerManager serializerManager,
                 final IntermediateDataIOFactory intermediateDataIOFactory,
                 final BroadcastManagerWorker broadcastManagerWorker,
                 final MetricManagerWorker metricMessageSender) {
  this.executorId = executorId;
  this.executorService = Executors.newCachedThreadPool(new BasicThreadFactory.Builder()
    .namingPattern("TaskExecutor thread-%d")
    .build());
  this.persistentConnectionToMasterMap = persistentConnectionToMasterMap;
  this.serializerManager = serializerManager;
  this.intermediateDataIOFactory = intermediateDataIOFactory;
  this.broadcastManagerWorker = broadcastManagerWorker;
  this.metricMessageSender = metricMessageSender;
  messageEnvironment.setupListener(MessageEnvironment.EXECUTOR_MESSAGE_LISTENER_ID, new ExecutorMessageReceiver());
}
 
Example #6
Source File: SlaveService.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Inject
public SlaveService(ApolloConfiguration apolloConfiguration, SlaveDao slaveDao, EnvironmentDao environmentDao) {
    this.slaveDao = requireNonNull(slaveDao);
    this.environmentDao = requireNonNull(environmentDao);
    this.apolloConfiguration = requireNonNull(apolloConfiguration);

    isSlave = apolloConfiguration.getSlave().isSlave();
    environmentIds = parseEnvironmentIds();

    if (isSlave && isEmpty(environmentIds)) {
        logger.error("Slave must be bundled with a valid list of environments! Bailing..");
        throw new RuntimeException("Could not understand slaves params");
    }

    slaveId = apolloConfiguration.getSlave().getSlaveId();
    keepaliveExecutorService = Executors.newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder()
                                        .namingPattern("slave-keepalive-pinger")
                                        .build());
}
 
Example #7
Source File: ExecutorWrapperImpl.java    From freeacs with MIT License 6 votes vote down vote up
protected ExecutorWrapperImpl(
    int numThreads,
    final String name,
    final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
  final BasicThreadFactory.Builder factory =
      new BasicThreadFactory.Builder().namingPattern(name + "-%d");
  if (uncaughtExceptionHandler != null) {
    factory.uncaughtExceptionHandler(uncaughtExceptionHandler);
  } else {
    factory.uncaughtExceptionHandler(
        (thread, error) -> {
          LOG.error("Thread " + thread.toString() + " failed to complete properly", error);
        });
  }
  executorService = Executors.newScheduledThreadPool(numThreads, factory.build());
}
 
Example #8
Source File: Main.java    From MyTv with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化应用数据
 */
private static void initDbData(final MyTvData data) {
	final TvService tvService = new TvServiceImpl();
	makeCache(tvService);

	// 启动抓取任务
	ExecutorService executorService = Executors
			.newSingleThreadExecutor(new BasicThreadFactory.Builder()
					.namingPattern("Mytv_Crawl_Task_%d").build());
	executorService.execute(new Runnable() {

		@Override
		public void run() {
			runCrawlTask(data, tvService);
		}
	});
	executorService.shutdown();
	// 启动每天定时任务
	logger.info("create everyday crawl task.");
	createEverydayCron(data, tvService);
}
 
Example #9
Source File: GremlinExecutor.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public GremlinExecutor create() {
    final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("gremlin-executor-default-%d").build();

    final AtomicBoolean poolCreatedByBuilder = new AtomicBoolean();
    final AtomicBoolean suppliedExecutor = new AtomicBoolean(true);
    final AtomicBoolean suppliedScheduledExecutor = new AtomicBoolean(true);

    final ExecutorService es = Optional.ofNullable(executorService).orElseGet(() -> {
        poolCreatedByBuilder.set(true);
        suppliedExecutor.set(false);
        return Executors.newScheduledThreadPool(4, threadFactory);
    });
    executorService = es;

    final ScheduledExecutorService ses = Optional.ofNullable(scheduledExecutorService).orElseGet(() -> {
        // if the pool is created by the builder and we need another just re-use it, otherwise create
        // a new one of those guys
        suppliedScheduledExecutor.set(false);
        return (poolCreatedByBuilder.get()) ?
                (ScheduledExecutorService) es : Executors.newScheduledThreadPool(4, threadFactory);
    });
    scheduledExecutorService = ses;

    return new GremlinExecutor(this, suppliedExecutor.get(), suppliedScheduledExecutor.get());
}
 
Example #10
Source File: ComponentsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void testConcurrency(BiConsumer<ExecutorService, Integer> taskCreator) throws InterruptedException {
    ExecutorService s = Executors.newFixedThreadPool(NUMBER_OF_THREADS,
      new BasicThreadFactory.Builder().daemon(true).uncaughtExceptionHandler((t, e) -> log.error(e.getMessage(), e)).build());
    this.remainingDeleteSubmissions = new CountDownLatch(NUMBER_OF_TASKS);

    for (int i = 0; i < NUMBER_OF_TASKS; i++) {
        taskCreator.accept(s, i);
    }

    try {
        assertTrue("Did not create all components in time", this.remainingDeleteSubmissions.await(100, TimeUnit.SECONDS));
        s.shutdown();
        assertTrue("Did not finish before timeout", s.awaitTermination(100, TimeUnit.SECONDS));
    } finally {
        s.shutdownNow();
    }
}
 
Example #11
Source File: SchedulerComponent.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void createExecutor() throws InvalidParameterException {
    int configuredAmountOfThreads = getParameterInt(PARAMETER_THREADS, false);
    int amountOfThreads = configuredAmountOfThreads < MIN_AMOUNT_OF_THREADS ? MIN_AMOUNT_OF_THREADS : configuredAmountOfThreads;
    BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern(getName() + "-Thread-%d").build();

    this.executorService = Executors.newScheduledThreadPool(amountOfThreads, threadFactory);
    logger.debug("Scheduler module is ready.");
}
 
Example #12
Source File: HadoopXmlResourceMonitor.java    From knox with Apache License 2.0 5 votes vote down vote up
public void setupMonitor() {
  if (monitoringInterval > 0) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder().namingPattern("ClouderaManagerDescriptorMonitor-%d").build());
    executorService.scheduleAtFixedRate(() -> monitorClouderaManagerDescriptors(null), 0, monitoringInterval, TimeUnit.MILLISECONDS);
    LOG.monitoringHadoopXmlResources(descriptorsDir);
  } else {
    LOG.disableMonitoringHadoopXmlResources();
  }
}
 
Example #13
Source File: AdvancedServiceDiscoveryConfigurationMonitor.java    From knox with Apache License 2.0 5 votes vote down vote up
private void setupMonitor() {
  if (monitoringInterval > 0) {
    final ScheduledExecutorService executorService = newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder().namingPattern("AdvancedServiceDiscoveryConfigurationMonitor-%d").build());
    executorService.scheduleAtFixedRate(() -> monitorAdvancedServiceConfigurations(), 0, monitoringInterval, TimeUnit.MILLISECONDS);
    LOG.monitorStarted(gatewayConfigurationDir, ADVANCED_CONFIGURATION_FILE_NAME_PREFIX);
  } else {
    LOG.disableMonitoring();
  }
}
 
Example #14
Source File: PeriodicReloadingTrigger.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default executor service. This method is called if no executor
 * has been passed to the constructor.
 *
 * @return the default executor service
 */
private static ScheduledExecutorService createDefaultExecutorService()
{
    final ThreadFactory factory =
            new BasicThreadFactory.Builder()
                    .namingPattern("ReloadingTrigger-%s").daemon(true)
                    .build();
    return Executors.newScheduledThreadPool(1, factory);
}
 
Example #15
Source File: MyWebSocketHandler.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 给所有在线用户发送消息
 *
 * @param message
 * @throws IOException
 */
public void broadcast(final TextMessage message) throws IOException {
	// 多线程群发
	for (Set<WebSocketSession> item : userSocketSessionMap.values()) {
		for (final WebSocketSession session : item) {
			if (session.isOpen()) {
				ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
					new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true)
						.build());
				for (int i = 0; i < 3; i++) {
					executorService.execute(new Runnable() {
						@Override
						public void run() {
							try {
								if (session.isOpen()) {
									logger.debug("broadcast output:" + message.toString());
									session.sendMessage(message);
								}
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					});
				}
			}
		}
	}
}
 
Example #16
Source File: ClouderaManagerClusterConfigurationMonitor.java    From knox with Apache License 2.0 5 votes vote down vote up
ClouderaManagerClusterConfigurationMonitor(final GatewayConfig config, final AliasService aliasService,
                                           final KeystoreService keystoreService) {
  // Initialize the config cache
  configCache = new ClusterConfigurationCache();

  // Initialize the persistent stores
  discoveryConfigStore = new DiscoveryConfigurationFileStore(config);
  serviceConfigStore = new ClusterConfigurationFileStore(config);

  // Configure the executor service
  ThreadFactory tf =
        new BasicThreadFactory.Builder().namingPattern("ClouderaManagerConfigurationMonitor-%d").build();
  this.executorService = Executors.newSingleThreadExecutor(tf);

  // Initialize the internal monitor
  internalMonitor = new PollingConfigurationAnalyzer(configCache, aliasService, keystoreService, this);

  // Override the default polling interval if it has been configured
  // (org.apache.knox.gateway.topology.discovery.cm.monitor.interval)
  int interval = config.getClusterMonitorPollingInterval(getType());
  if (interval > 0) {
    setPollingInterval(interval);
  }

  // Load any previously-persisted discovery configuration data
  loadDiscoveryConfiguration();

  // Load any previously-persisted cluster service configuration data
  loadServiceConfiguration();
}
 
Example #17
Source File: Lang3UtilsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testBuildDefaults() {
    BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder();
    BasicThreadFactory factory = builder.build();
    assertNull("No naming pattern set Yet", factory.getNamingPattern());
    BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build();
    assertNotNull("Got a naming pattern", factory2.getNamingPattern());
    assertEquals("sampleNamingPattern", factory2.getNamingPattern());

}
 
Example #18
Source File: ProcessorHelper.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static <T> ExecutorService createProcessors(int threadCount, BlockingQueue<T> queue, Consumer<T> consumer, String name) {
    ThreadFactory factory = new BasicThreadFactory.Builder().namingPattern(name + "-%d").build();
    ExecutorService result = Executors.newFixedThreadPool(threadCount, factory);
    for (int i = 0; i < threadCount; i++) {

        result.submit(new Processor(queue, consumer, name));
    }
    return result;
}
 
Example #19
Source File: BasicThreadFactoryUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenBasicThreadFactoryInstance_whenCalledBuilder_thenCorrect() {
    BasicThreadFactory factory = new BasicThreadFactory.Builder()
        .namingPattern("workerthread-%d")
        .daemon(true)
        .priority(Thread.MAX_PRIORITY)
        .build();
    assertThat(factory).isInstanceOf(BasicThreadFactory.class);
}
 
Example #20
Source File: SQLDB.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SQLDB(
        Supplier<UUID> serverUUIDSupplier,
        Locale locale,
        PlanConfig config,
        RunnableFactory runnableFactory,
        PluginLogger logger,
        ErrorLogger errorLogger
) {
    this.serverUUIDSupplier = serverUUIDSupplier;
    this.locale = locale;
    this.config = config;
    this.runnableFactory = runnableFactory;
    this.logger = logger;
    this.errorLogger = errorLogger;

    devMode = config.isTrue(PluginSettings.DEV_MODE);

    this.transactionExecutorServiceProvider = () -> {
        String nameFormat = "Plan " + getClass().getSimpleName() + "-transaction-thread-%d";
        return Executors.newSingleThreadExecutor(new BasicThreadFactory.Builder()
                .namingPattern(nameFormat)
                .uncaughtExceptionHandler((thread, throwable) -> {
                    if (devMode) {
                        errorLogger.log(L.WARN, throwable, ErrorContext.builder()
                                .whatToDo("THIS ERROR IS ONLY LOGGED IN DEV MODE")
                                .build());
                    }
                }).build());
    };
}
 
Example #21
Source File: Processing.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected ExecutorService createExecutor(int i, String s) {
    return Executors.newFixedThreadPool(i,
            new BasicThreadFactory.Builder()
                    .namingPattern(s)
                    .uncaughtExceptionHandler((thread, throwable) ->
                            errorLogger.log(L.WARN, throwable, ErrorContext.builder().build())
                    ).build());
}
 
Example #22
Source File: DataCenterInfoWatchdog.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("SendDataCenterInfo-schedule-pool-%d").daemon(true).build());
    scheduledExecutorService.scheduleAtFixedRate(() -> applicationEventPublisher.publishEvent(DataCenterInfoEvent.builder()
            .name(goPushDataCenterConfig.getName())
            .dataCenterInfo(watch())
            .build()), delay, delay, TimeUnit.MILLISECONDS);
}
 
Example #23
Source File: EventDispatcher.java    From bird-java with MIT License 5 votes vote down vote up
@PostConstruct
public void initHandlerStoreThread() {
    if (handlerStore != null) {
        ScheduledThreadPoolExecutor poolExecutor = new ScheduledThreadPoolExecutor(2, (new BasicThreadFactory.Builder()).build());
        poolExecutor.scheduleAtFixedRate(new EventHandleStoreConsumer(), 0, 10, TimeUnit.SECONDS);
    }
}
 
Example #24
Source File: ThreadPoolConfig.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 执行周期性或定时任务
 */
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService()
{
    return new ScheduledThreadPoolExecutor(corePoolSize,
            new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build())
    {
        @Override
        protected void afterExecute(Runnable r, Throwable t)
        {
            super.afterExecute(r, t);
            Threads.printException(r, t);
        }
    };
}
 
Example #25
Source File: BatchedEmbedder.java    From vividus with Apache License 2.0 5 votes vote down vote up
private ExecutorService createExecutorService(int threads)
{
    ThreadFactory threadFactory = new BasicThreadFactory.Builder()
            .namingPattern(batch + "-thread-%d")
            .build();
    return Executors.newFixedThreadPool(threads, threadFactory);
}
 
Example #26
Source File: ExecutorUtil.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
public static ScheduledExecutorService newScheduledThreadPool(int size,
                                                              String name) {
    ThreadFactory factory = new BasicThreadFactory.Builder()
                                                  .namingPattern(name)
                                                  .build();
    return Executors.newScheduledThreadPool(size, factory);
}
 
Example #27
Source File: ThreadPoolConfig.java    From v-mock with MIT License 5 votes vote down vote up
/**
 * 执行周期性或定时任务
 */
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
    return new ScheduledThreadPoolExecutor(corePoolSize,
            new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            log.error(ExceptionUtil.getMessage(t));
        }
    };
}
 
Example #28
Source File: InspectableThreadPoolExecutor.java    From inception with Apache License 2.0 5 votes vote down vote up
private static ThreadFactory buildThreadFactory()
{
    return new BasicThreadFactory.Builder()
            .daemon(true)
            .priority(Thread.MIN_PRIORITY)
            .build();
}
 
Example #29
Source File: ThreadPoolUtils.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public static ExecutorService createExecutorService(int corePoolSize,String threadNamingPattern, int workQueue){
    if (corePoolSize < 1){
    	corePoolSize = 5;
    }

    if (workQueue < 1){
    	workQueue = 50;
    }

    return new ThreadPoolExecutor(corePoolSize, corePoolSize * 10, 100L, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<Runnable>(workQueue),
            new BasicThreadFactory.Builder().namingPattern(threadNamingPattern).daemon(true).build(), new ThreadPoolExecutor.AbortPolicy());
}
 
Example #30
Source File: ThreadPoolUtils.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public static ExecutorService createCacheExecutorService(int corePoolSize, int maximumPoolSize, String threadNamingPattern) {
	if(corePoolSize < 1) {
		corePoolSize = 5;
	}
	if(maximumPoolSize < 1) {
		maximumPoolSize = 100;
	}
	return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 100L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(),
			new BasicThreadFactory.Builder().namingPattern(threadNamingPattern).daemon(true).build(), new ThreadPoolExecutor.AbortPolicy());
}