public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException { System.err.println("* Opening socket " + isa); Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort()); s.setKeepAlive(true); s.setTcpNoDelay(true); System.err.println("* Opening channel"); OutputStream outputStream = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputStream); dos.writeUTF("Protocol:CLI-connect"); ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() { public Thread newThread ( Runnable r ) { Thread t = new Thread(r, "Channel"); t.setDaemon(true); return t; } }); Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream); System.err.println("* Channel open"); return c; }
private void scheduleClockUpdating() { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "System Clock"); thread.setDaemon(true); return thread; } }); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { now.set(System.currentTimeMillis()); } }, precision, precision, TimeUnit.MILLISECONDS); }
@Override public void afterPropertiesSet() throws NamingException { if (this.jndiName != null) { try { this.threadFactory = this.jndiLocator.lookup(this.jndiName, ThreadFactory.class); } catch (NamingException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to find [java:comp/DefaultManagedThreadFactory] in JNDI", ex); } if (logger.isInfoEnabled()) { logger.info("Could not find default managed thread factory in JNDI - " + "proceeding with default local thread factory"); } } } }
private static PooledExecutorWithDMStats createExecutor(PoolStatHelper poolHelper, final ThreadGroup threadGroup) { ThreadFactory factory = new ThreadFactory() { private final AtomicInteger threadNum = new AtomicInteger(); public Thread newThread(Runnable r) { Thread thread = new Thread(threadGroup, r, "locator request thread[" + threadNum.incrementAndGet() + "]"); thread.setDaemon(true); return thread; } }; return new PooledExecutorWithDMStats(new SynchronousQueue(), MAX_POOL_SIZE, poolHelper, factory, POOL_IDLE_TIMEOUT, new ThreadPoolExecutor.CallerRunsPolicy()); }
@Test public void customEventLoopGroup_NotClosedWhenClientIsClosed() throws Exception { ThreadFactory threadFactory = spy(new CustomThreadFactory()); // Cannot use DefaultEventLoopGroupFactory because the concrete // implementation it creates is platform-dependent and could be a final // (i.e. non-spyable) class. EventLoopGroup eventLoopGroup = spy(new NioEventLoopGroup(0, threadFactory)); EventLoopGroupConfiguration eventLoopGroupConfiguration = EventLoopGroupConfiguration.builder() .eventLoopGroup(eventLoopGroup) .build(); SdkAsyncHttpClient customClient = NettySdkHttpClientFactory.builder() .trustAllCertificates(true) .eventLoopGroupConfiguration(eventLoopGroupConfiguration) .build() .createHttpClient(); makeSimpleRequest(customClient); customClient.close(); Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any()); Mockito.verify(eventLoopGroup, never()).shutdownGracefully(); }
public DatadogMeterRegistry(DatadogConfig config, Clock clock, ThreadFactory threadFactory) { super(config, clock); this.config().namingConvention(new DatadogNamingConvention()); try { this.postTimeSeriesEndpoint = URI.create(config.uri() + "/api/v1/series?api_key=" + config.apiKey()).toURL(); } catch (MalformedURLException e) { // not possible throw new RuntimeException(e); } this.config = config; start(threadFactory); }
@Override protected void serviceInit(Configuration conf) throws Exception { ThreadFactory tf = new ThreadFactoryBuilder() .setNameFormat("DeletionService #%d") .build(); if (conf != null) { sched = new DelServiceSchedThreadPoolExecutor( conf.getInt(YarnConfiguration.NM_DELETE_THREAD_COUNT, YarnConfiguration.DEFAULT_NM_DELETE_THREAD_COUNT), tf); debugDelay = conf.getInt(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 0); } else { sched = new DelServiceSchedThreadPoolExecutor( YarnConfiguration.DEFAULT_NM_DELETE_THREAD_COUNT, tf); } sched.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); sched.setKeepAliveTime(60L, SECONDS); if (stateStore.canRecover()) { recover(stateStore.loadDeletionServiceState()); } super.serviceInit(conf); }
/** * Конструктор для тестирования * * @param queueRegistry хранилище очередей * @param defaultTaskLifecycleListener слушатель жизненного цикла задачи * @param defaultThreadLifecycleListener слушатель жизненного цикла потока очереди * @param threadFactoryProvider фабрика фабрик создания потоков * @param queueThreadPoolFactory фабрика для создания пула обработки очередей * @param queueLoopFactory фабрика для создания {@link QueueLoop} * @param queueRunnerFactory фабрика для создания {@link QueueRunner} */ QueueExecutionPool(@Nonnull QueueRegistry queueRegistry, @Nonnull TaskLifecycleListener defaultTaskLifecycleListener, @Nonnull ThreadLifecycleListener defaultThreadLifecycleListener, @Nonnull BiFunction<QueueLocation, QueueShardId, ThreadFactory> threadFactoryProvider, @Nonnull BiFunction<Integer, ThreadFactory, ExecutorService> queueThreadPoolFactory, @Nonnull Function<ThreadLifecycleListener, QueueLoop> queueLoopFactory, @Nonnull Function<ShardPoolInstance, QueueRunner> queueRunnerFactory) { this.queueRegistry = Objects.requireNonNull(queueRegistry); this.defaultTaskLifecycleListener = Objects.requireNonNull(defaultTaskLifecycleListener); this.defaultThreadLifecycleListener = Objects.requireNonNull(defaultThreadLifecycleListener); this.queueThreadPoolFactory = Objects.requireNonNull(queueThreadPoolFactory); this.threadFactoryProvider = Objects.requireNonNull(threadFactoryProvider); this.queueLoopFactory = Objects.requireNonNull(queueLoopFactory); this.queueRunnerFactory = Objects.requireNonNull(queueRunnerFactory); }
public ServiceCacheImplProxy(ServiceDiscoveryImpl<T> discovery, String name, ThreadFactory threadFactory) { this.serviceCacheImpl = new ServiceCacheImpl<T>(discovery, name, threadFactory); try { Field privateListenerContainerField = ServiceCacheImpl.class.getDeclaredField("listenerContainer"); privateListenerContainerField.setAccessible(true); this.listenerContainer = (ListenerContainer)privateListenerContainerField.get(serviceCacheImpl); } catch (NoSuchFieldException | IllegalAccessException e) { log.error("Failed to construct Service Cache. Container listeners is null."); } Preconditions.checkNotNull(discovery, "discovery cannot be null"); Preconditions.checkNotNull(name, "name cannot be null"); Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); Preconditions.checkNotNull(this.listenerContainer, "container of listeners can not be null"); this.discovery = discovery; this.cache = new PathChildrenCache(discovery.getClient(), discovery.pathForName(name), true, threadFactory); this.cache.getListenable().addListener(this); }
private static ExecutorService getExecutor() { synchronized (sExecutorServiceLock) { if (sExecutorService == null) { ThreadFactory threadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "HttpUrlConnection #" + mCount.getAndIncrement()); // Note that this thread is not doing actual networking. // It's only a controller. thread.setPriority(Thread.NORM_PRIORITY); return thread; } }; sExecutorService = Executors.newCachedThreadPool(threadFactory); } return sExecutorService; } }
/** * Create a new server listener. * @param serverConnector connector * @param socketFactory socket factory * @param authenticator authenticator * @param accessController access controller * @param threadPriority thread priority * @throws IOException if an I/O error occurs when constructing the server listener */ ServerListener(final ServerConnector serverConnector, final JMXSocketFactory socketFactory, final JMXAuthenticator authenticator, final JMXAccessController accessController, final int threadPriority) throws IOException { this.serverConnector = serverConnector; this.authenticator = authenticator; this.accessController = accessController; serverId = SERVER_ID.getAndIncrement(); // Setup executor service final ThreadFactory threadFactory = new ConnectionThreadFactory(serverId, threadPriority); executorService = Executors.newCachedThreadPool(threadFactory); // Setup server socket serverSocket = socketFactory.createServerSocket(serverConnector.getAddress()); serverConnector.updateAddress(serverSocket.getLocalPort()); serverSocket.setSoTimeout(0); }
/** * @deprecated This method is only used from configuration modules and thus callers of it * should use service injection to make the executor configurable. */ @Deprecated public static synchronized ListeningExecutorService getDefaultCommitExecutor() { if (COMMIT_EXECUTOR == null) { final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("md-sal-binding-commit-%d").build(); /* * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction * ordering guarantees, which means that using a concurrent threadpool results * in application data being committed in random order, potentially resulting * in inconsistent data being present. Once proper primitives are introduced, * concurrency can be reintroduced. */ final ExecutorService executor = Executors.newSingleThreadExecutor(factory); COMMIT_EXECUTOR = MoreExecutors.listeningDecorator(executor); } return COMMIT_EXECUTOR; }
CustomTPE(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); }
public DebuggableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); allowCoreThreadTimeOut(true); // block task submissions until queue has room. // this is fighting TPE's design a bit because TPE rejects if queue.offer reports a full queue. // we'll just override this with a handler that retries until it gets in. ugly, but effective. // (there is an extensive analysis of the options here at // http://today.java.net/pub/a/today/2008/10/23/creating-a-notifying-blocking-thread-pool-executor.html) this.setRejectedExecutionHandler(blockingExecutionHandler); }
private static ThreadFactory getThreadFactory(final String name) { return new ThreadFactory() { private int threadCount = 1; public Thread newThread(Runnable r) { Thread thread = new Thread(r); if (name != null) { thread.setName(name + "-" + threadCount++); } thread.setPriority(Thread.MAX_PRIORITY); return thread; } }; }
@PostConstruct public void initMethod() { ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("heart-beat-executor-%d") .setDaemon(true) .build(); this.heartbeatExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),threadFactory); }
/** * Creates a proper Cached Thread Pool. Tasks will reuse cached threads if available * or create new threads until the core pool is full. tasks will then be queued. If an * task cannot be queued, a new thread will be created unless this would exceed max pool * size, then the task will be rejected. Threads will time out after 1 second. * * Core thread timeout is only available on android-9+. * * @param threadFactory the factory to use when creating new threads * @return the newly created thread pool */ public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { ThreadPoolExecutor executor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); allowCoreThreadTimeout(executor, true); return executor; }
/** * @param corePoolSize * @param threadFactory */ public ScheduledThreadPoolExecutorWithKeepAlive(int corePoolSize, long keepAlive, TimeUnit timeUnit, ThreadFactory threadFactory) { super(0, corePoolSize - 1, keepAlive, timeUnit, new SynchronousQueue(), threadFactory, new BlockCallerPolicy()); timer = new ScheduledThreadPoolExecutor(1, threadFactory) { @Override protected void terminated() { super.terminated(); ScheduledThreadPoolExecutorWithKeepAlive.super.shutdown(); } }; }
@VisibleForTesting RevivingScheduledExecutor( final ThreadFactory threadFactory, final String threadName, final long initialDelayMs, final long timeoutMs) { super(0); checkNotNull(threadFactory, "threadFactory must not be null"); INSTANCE_COUNTER.incrementAndGet(); this.initialDelayMs = initialDelayMs; this.timeoutMs = timeoutMs; setRemoveOnCancelPolicy(true); setThreadFactory( new ThreadFactory() { @Override public Thread newThread(Runnable r) { logger.debug("Creating new thread for: {}", threadName); Thread thread = threadFactory.newThread(r); try { thread.setName(threadName); thread.setDaemon(true); } catch (AccessControlException ignore) { // Unsupported on App Engine. } if (requestedRestart.getAndSet(false)) { afterRestart(); } return thread; } }); }
@Provides @Singleton ThreadFactory threadFactory(Thread.UncaughtExceptionHandler exceptionHandler) { return runnable -> { final Thread thread = new Thread(runnable); thread.setUncaughtExceptionHandler(exceptionHandler); return thread; }; }
@Test public void testTokenChangeListenerThread() throws InterruptedException, IOException { MockGoogleCredentials credentials = new MockGoogleCredentials(); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(credentials) .build(); FirebaseApp app = FirebaseApp.initializeApp(options); // Disable proactive token refresh, so only explicit refresh events are in play. ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("auth-token-provider-thread") .setDaemon(true) .build(); ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory); try { JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, executor, false); final AtomicReference<String> result = new AtomicReference<>(); final Semaphore semaphore = new Semaphore(0); provider.addTokenChangeListener(new AuthTokenProvider.TokenChangeListener() { @Override public void onTokenChange(String token) { result.set(Thread.currentThread().getName()); semaphore.release(); } }); credentials.refresh(); assertTrue(semaphore.tryAcquire(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)); assertEquals("auth-token-provider-thread", result.get()); } finally { executor.shutdownNow(); } }
@Test public void testAppEngineDelayedCallable() throws InterruptedException, TimeoutException, ExecutionException { final AtomicInteger threads = new AtomicInteger(0); RevivingScheduledExecutor executor = new RevivingScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { threads.incrementAndGet(); return THREAD_FACTORY.newThread(r); } }, "testAppEngineDelayedCallable", 0, 100); ScheduledFuture<Boolean> future = executor.schedule( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return true; } }, 750, TimeUnit.MILLISECONDS); try { Assert.assertTrue(future.get(1, TimeUnit.SECONDS)); Assert.assertTrue(threads.get() >= 2); } finally { executor.shutdownNow(); } }
static ThreadPoolExecutor getOpenAndCloseThreadPool(int maxThreads, final String threadNamePrefix) { return Threads .getBoundedCachedThreadPool(maxThreads, 30L, TimeUnit.SECONDS, new ThreadFactory() { private int count = 1; @Override public Thread newThread(Runnable r) { return new Thread(r, threadNamePrefix + "-" + count++); } }); }
public SignalFxMeterRegistry(SignalFxConfig config, Clock clock, ThreadFactory threadFactory) { super(config, clock); this.config = config; try { this.postTimeSeriesEndpoint = URI.create(config.uri() + "/datapoint").toURL(); } catch (MalformedURLException e) { // not possible throw new RuntimeException(e); } config().namingConvention(new SignalFxNamingConvention()); start(threadFactory); }
public static ThreadFactory threadFactory(final String name, final boolean daemon) { return new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread result = new Thread(runnable, name); result.setDaemon(daemon); return result; } }; }
public ScrollPerfExecutorSupplier(int numCpuBoundThreads, int numDecodingThread) { ThreadFactory backgroundPriorityThreadFactory = new PriorityThreadFactory(Process.THREAD_PRIORITY_BACKGROUND); mIoBoundExecutor = Executors.newFixedThreadPool(NUM_IO_BOUND_THREADS); mDecodeExecutor = Executors.newFixedThreadPool( numDecodingThread, backgroundPriorityThreadFactory); mBackgroundExecutor = Executors.newFixedThreadPool( numCpuBoundThreads, backgroundPriorityThreadFactory); mLightWeightBackgroundExecutor = Executors.newFixedThreadPool( NUM_LIGHTWEIGHT_BACKGROUND_THREADS, backgroundPriorityThreadFactory); }
public void testPriority_custom() { for (int i = Thread.MIN_PRIORITY; i <= Thread.MAX_PRIORITY; i++) { ThreadFactory factory = builder.setPriority(i).build(); Thread thread = factory.newThread(monitoredRunnable); assertEquals(i, thread.getPriority()); } }
public static final ThreadFactory getNamedThreadFactory(final String threadNameTemplate) { final AtomicLong count = new AtomicLong(1); return new ThreadFactory() { public Thread newThread(final Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(new BackgroundPriorityRunnable() { public void onRun() { runnable.run(); } }); thread.setName(threadNameTemplate + count.getAndIncrement()); return thread; } }; }
void test(final Class<?> exceptionClass, final ThreadFactory failingThreadFactory) throws Throwable { ThreadFactory flakyThreadFactory = new ThreadFactory() { int seq = 0; public Thread newThread(Runnable r) { if (seq++ < 4) return new Thread(r); else return failingThreadFactory.newThread(r); }}; ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue(), flakyThreadFactory); try { for (int i = 0; i < 8; i++) pool.submit(new Runnable() { public void run() {} }); check(exceptionClass == null); } catch (Throwable t) { /* t.printStackTrace(); */ check(exceptionClass.isInstance(t)); } pool.shutdown(); check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); }
public final void setThreadFactory(ThreadFactory threadFactory) { if(threadFactory==null) { throw new NullArgumentException("threadFactory is null"); } this.threadFactory = threadFactory; }
/** * 这个方法必须被调用后 FinalBitmap 配置才能有效 * * @return */ private FinalBitmap init() { mConfig.init(); BitmapCache.ImageCacheParams imageCacheParams = new BitmapCache.ImageCacheParams(mConfig.cachePath); if (mConfig.memCacheSizePercent > 0.05 && mConfig.memCacheSizePercent < 0.8) { imageCacheParams.setMemCacheSizePercent(mContext, mConfig.memCacheSizePercent); } else { if (mConfig.memCacheSize > 1024 * 1024 * 2) { imageCacheParams.setMemCacheSize(mConfig.memCacheSize); } else { // 设置默认的内存缓存大小 imageCacheParams.setMemCacheSizePercent(mContext, 0.3f); } } if (mConfig.diskCacheSize > 1024 * 1024 * 5) imageCacheParams.setDiskCacheSize(mConfig.diskCacheSize); mImageCache = new BitmapCache(imageCacheParams); bitmapLoadAndDisplayExecutor = Executors.newFixedThreadPool(mConfig.poolSize, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); // 设置线程的优先级别,让线程先后顺序执行(级别越高,抢到cpu执行的时间越多) t.setPriority(Thread.NORM_PRIORITY - 1); return t; } }); new CacheExecutecTask().execute(CacheExecutecTask.MESSAGE_INIT_DISK_CACHE); return this; }
public static ExecutorService createThreadPool(Properties prop) { int minPoolSize = Integer.parseInt(prop.getProperty("min_pool_size", "5")); int maxPoolSize = Integer.parseInt(prop.getProperty("max_pool_size", "10")); int keepAliveTime = Integer.parseInt(prop.getProperty("keep_alive_secs", "10")); ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "Message_Handler_Pool_Thread_" + threadId.incrementAndGet()); if (thread.isDaemon()) thread.setDaemon(false); if (thread.getPriority() != Thread.NORM_PRIORITY) thread.setPriority(Thread.NORM_PRIORITY); return thread; } }; ExecutorService taskExecutor = new ThreadPoolExecutor(minPoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); // ExecutorService executorService1 = Executors.newSingleThreadExecutor(); return taskExecutor; }
public static ThreadFactory threadFactory(final String name, final boolean daemon) { return new ThreadFactory() { @Override public Thread newThread(@NonNull Runnable runnable) { final Thread result = new Thread(runnable, name); result.setDaemon(daemon); return result; } }; }
public static ThreadFactory getThreadFactory(final String name, final UncaughtExceptionHandler handler) { return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(null, r, name, 1024*1024); t.setDaemon(true); t.setUncaughtExceptionHandler(handler); return t; } }; }
/** * * @param name * @param priority * @return */ public static ThreadFactory newDaemonThreadFactory(final String name, final int priority) { return new ThreadFactory() { @Override public Thread newThread(Runnable r) { return newDaemonThread(r, name, priority); } }; }
public void testGetExitingScheduledExcutorService_executorDelegatesToOriginal() { TestApplication application = new TestApplication(); ScheduledThreadPoolExecutor executor = mock(ScheduledThreadPoolExecutor.class); ThreadFactory threadFactory = mock(ThreadFactory.class); when(executor.getThreadFactory()).thenReturn(threadFactory); application.getExitingScheduledExecutorService(executor).execute(EMPTY_RUNNABLE); verify(executor).execute(EMPTY_RUNNABLE); }
public NettyRemotingClient(NettyClientConfig nettyClientConfig) { this.nettyClientConfig = nettyClientConfig; this.eventLoopGroupWorker = new NioEventLoopGroup(1,new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, String.format("NettyClientSelector_%d",this.threadIndex.incrementAndGet())); } }); }
public void localizeFiles() throws IOException { ThreadFactory tf = new ThreadFactoryBuilder() .setNameFormat("Localizer #%d").build(); ExecutorService newFixedThreadPool = Executors.newFixedThreadPool( localizeThreads, tf); for (LocalizationResource resource : resources) { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); Configuration conf = new Configuration(); FSDownload fsDownload = new FSDownload( FileContext.getLocalFSFileContext(), ugi, conf, new Path( localizationDir), resource); newFixedThreadPool.submit(fsDownload); } newFixedThreadPool.shutdown(); }
public static ThreadFactory daemonThreadFactory(final String name) { return new ThreadFactory() { private int nextId = 0; public synchronized Thread newThread(Runnable r) { Thread thread = new Thread(r, name + "-" + (nextId++)); thread.setDaemon(true); return thread; } }; }
public void testNameFormatWithPercentD_custom() { String format = "super-duper-thread-%d"; ThreadFactory factory = builder.setNameFormat(format).build(); for (int i = 0; i < 11; i++) { assertEquals(rootLocaleFormat(format, i), factory.newThread(monitoredRunnable).getName()); } }