Java Code Examples for java.util.concurrent.ThreadFactory

The following examples show how to use java.util.concurrent.ThreadFactory. These examples are extracted from open source projects. 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 Project: jdk8u-jdk   Source File: RuntimeUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
private RuntimeUtil() {
    scheduler = new ScheduledThreadPoolExecutor(
        schedulerThreads,
        new ThreadFactory() {
            private final AtomicInteger count = new AtomicInteger(0);
            public Thread newThread(Runnable runnable) {
                try {
                    return AccessController.doPrivileged(
                        new NewThreadAction(runnable,
                            "Scheduler(" + count.getAndIncrement() + ")",
                            true));
                } catch (Throwable t) {
                    runtimeLog.log(Level.WARNING,
                                   "scheduler thread factory throws", t);
                    return null;
                }
            }
        });
    /*
     * We would like to allow the scheduler's threads to terminate
     * if possible, but a bug in DelayQueue.poll can cause code
     * like this to result in a busy loop:
     */
    // stpe.setKeepAliveTime(10, TimeUnit.MINUTES);
    // stpe.allowCoreThreadTimeOut(true);
}
 
Example 2
Source Project: Maying   Source File: ShadowsocksApplication.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * /// xhao: init variable
 */
private void initVariable() {
    tracker = GoogleAnalytics.getInstance(this).newTracker(R.xml.tracker);
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    editor = settings.edit();

    profileManager = new ProfileManager(new DBHelper(this));
    ssrsubManager = new SSRSubManager(new DBHelper(this));
    resources = getResources();

    mThreadPool = new ScheduledThreadPoolExecutor(10, new ThreadFactory() {
        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("co.tgbot.peekfun-thread");
            return thread;
        }
    });
}
 
Example 3
Source Project: hadoop-ozone   Source File: BackgroundService.java    License: Apache License 2.0 6 votes vote down vote up
public BackgroundService(String serviceName, long interval,
    TimeUnit unit, int threadPoolSize, long serviceTimeout) {
  this.interval = interval;
  this.unit = unit;
  this.serviceName = serviceName;
  this.serviceTimeout = serviceTimeout;
  threadGroup = new ThreadGroup(serviceName);
  ThreadFactory tf = r -> new Thread(threadGroup, r);
  threadFactory = new ThreadFactoryBuilder()
      .setThreadFactory(tf)
      .setDaemon(true)
      .setNameFormat(serviceName + "#%d")
      .build();
  exec = Executors.newScheduledThreadPool(threadPoolSize, threadFactory);
  service = new PeriodicalTask();
}
 
Example 4
Source Project: hadoop-ozone   Source File: TableCacheImpl.java    License: Apache License 2.0 6 votes vote down vote up
public TableCacheImpl(CacheCleanupPolicy cleanupPolicy) {

    // As for full table cache only we need elements to be inserted in sorted
    // manner, so that list will be easy. For other we can go with Hash map.
    if (cleanupPolicy == CacheCleanupPolicy.NEVER) {
      cache = new ConcurrentSkipListMap<>();
    } else {
      cache = new ConcurrentHashMap<>();
    }
    epochEntries = new ConcurrentSkipListSet<>();
    // Created a singleThreadExecutor, so one cleanup will be running at a
    // time.
    ThreadFactory build = new ThreadFactoryBuilder().setDaemon(true)
        .setNameFormat("PartialTableCache Cleanup Thread - %d").build();
    executorService = Executors.newSingleThreadExecutor(build);
    this.cleanupPolicy = cleanupPolicy;
  }
 
Example 5
Source Project: hadoop   Source File: S3AFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely,
 * with a common prefix.
 * @param prefix The prefix of every created Thread's name
 * @return a {@link java.util.concurrent.ThreadFactory} that names threads
 */
public static ThreadFactory getNamedThreadFactory(final String prefix) {
  SecurityManager s = System.getSecurityManager();
  final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread()
      .getThreadGroup();

  return new ThreadFactory() {
    final AtomicInteger threadNumber = new AtomicInteger(1);
    private final int poolNum = poolNumber.getAndIncrement();
    final ThreadGroup group = threadGroup;

    @Override
    public Thread newThread(Runnable r) {
      final String name = prefix + "-pool" + poolNum + "-t" + threadNumber.getAndIncrement();
      return new Thread(group, r, name);
    }
  };
}
 
Example 6
Source Project: AppUpdate   Source File: HttpDownloadManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void download(String apkUrl, String apkName, OnDownloadListener listener) {
    this.apkUrl = apkUrl;
    this.apkName = apkName;
    this.listener = listener;
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(Constant.THREAD_NAME);
            return thread;
        }
    });
    executor.execute(runnable);
}
 
Example 7
public ThrottleDataCleanUpTask() {

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new ThreadFactory() {

            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName("Throttle Cleanup Task");
                return t;
            }
        });

        int throttleFrequency = ThrottleConfigHolder.getInstance().getThrottleFrequency();

        if (log.isDebugEnabled()) {
            log.debug("Throttling Cleanup Task Frequency set to " + throttleFrequency);
        }

        executor.scheduleAtFixedRate(new CleanupTask(), throttleFrequency, throttleFrequency, TimeUnit.SECONDS);

    }
 
Example 8
@Test
@SuppressWarnings("serial")
public void testShutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
	final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);

	ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
		@Override
		protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
			return executor;
		}
	};
	factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
		new NoOpScheduledExecutorTask()
	});
	factory.afterPropertiesSet();
	factory.destroy();

	verify(executor).shutdownNow();
}
 
Example 9
Source Project: xian   Source File: ThreadUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static ThreadFactory newGenericThreadFactory(String processName)
{
    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler()
    {
        @Override
        public void uncaughtException(Thread t, Throwable e)
        {
            log.error("Unexpected exception in thread: " + t, e);
            Throwables.propagate(e);
        }
    };
    return new ThreadFactoryBuilder()
        .setNameFormat(processName + "-%d")
        .setDaemon(true)
        .setUncaughtExceptionHandler(uncaughtExceptionHandler)
        .build();
}
 
Example 10
public void test() throws Exception {
    TestEventFactory factory = new TestEventFactory();

    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    Disruptor<TestEvent> disruptor = new Disruptor<>(factory, 1024, threadFactory);

    disruptor.handleEventsWith(new TestEventHandler());

    disruptor.start();

    RingBuffer<TestEvent> ringBuffer = disruptor.getRingBuffer();

    TestEventProducerWithTranslator producer = new TestEventProducerWithTranslator(ringBuffer);

    ByteBuffer bb = ByteBuffer.allocate(8);
    for (long l = 0; true; l++) {
        bb.putLong(0, l);
        producer.onData(bb);
        Thread.sleep(1000);
    }
}
 
Example 11
Source Project: openjdk-jdk9   Source File: RuntimeUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
private RuntimeUtil() {
    scheduler = new ScheduledThreadPoolExecutor(
        schedulerThreads,
        new ThreadFactory() {
            private final AtomicInteger count = new AtomicInteger(0);
            public Thread newThread(Runnable runnable) {
                try {
                    return AccessController.doPrivileged(
                        new NewThreadAction(runnable,
                            "Scheduler(" + count.getAndIncrement() + ")",
                            true));
                } catch (Throwable t) {
                    runtimeLog.log(Level.WARNING,
                                   "scheduler thread factory throws", t);
                    return null;
                }
            }
        });
    /*
     * We would like to allow the scheduler's threads to terminate
     * if possible, but a bug in DelayQueue.poll can cause code
     * like this to result in a busy loop:
     */
    // stpe.setKeepAliveTime(10, TimeUnit.MINUTES);
    // stpe.allowCoreThreadTimeOut(true);
}
 
Example 12
Source Project: micrometer   Source File: AppOpticsMeterRegistry.java    License: Apache License 2.0 6 votes vote down vote up
protected AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient) {
    super(config, clock);

    config().namingConvention(new AppOpticsNamingConvention());

    this.config = config;
    this.httpClient = httpClient;

    config().meterFilter(new MeterFilter() {
        @Override
        public Meter.Id map(Meter.Id id) {
            if (id.getName().startsWith("system.")) {
                return id.withName("micrometer." + id.getName());
            }
            return id;
        }
    });

    start(threadFactory);
}
 
Example 13
Source Project: ShadowsocksRR   Source File: ShadowsocksApplication.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * /// xhao: init variable
 */
private void initVariable() {
    tracker = GoogleAnalytics.getInstance(this).newTracker(R.xml.tracker);
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    editor = settings.edit();

    profileManager = new ProfileManager(new DBHelper(this));
    ssrsubManager = new SSRSubManager(new DBHelper(this));
    resources = getResources();

    mThreadPool = new ScheduledThreadPoolExecutor(10, new ThreadFactory() {
        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("shadowsocks-thread");
            return thread;
        }
    });
}
 
Example 14
Source Project: micrometer   Source File: NewRelicMeterRegistry.java    License: Apache License 2.0 6 votes vote down vote up
NewRelicMeterRegistry(NewRelicConfig config, @Nullable NewRelicClientProvider clientProvider,
            NamingConvention namingConvention, Clock clock, ThreadFactory threadFactory) {
    super(config, clock);

    if (clientProvider == null) {
        //default to Insight API client provider if not specified in config or provided
        clientProvider = (config.clientProviderType() == ClientProviderType.INSIGHTS_AGENT)
                ? new NewRelicInsightsAgentClientProvider(config)
                : new NewRelicInsightsApiClientProvider(config);
    }

    this.clientProvider = clientProvider;

    thisConfig = new Config() {
        @Override
        public Config namingConvention(NamingConvention convention) {
            NewRelicMeterRegistry.this.clientProvider.setNamingConvention(convention);
            return super.namingConvention(convention);
        }
    };

    config().namingConvention(namingConvention);
    start(threadFactory);
}
 
Example 15
@VisibleForTesting
MetricReporter(
    MetricWriter metricWriter,
    long writeInterval,
    ThreadFactory threadFactory,
    MetricRegistry metricRegistry,
    BlockingQueue<Optional<ImmutableList<MetricPoint<?>>>> writeQueue) {
  checkArgument(writeInterval > 0, "writeInterval must be greater than zero");

  this.metricWriter = metricWriter;
  this.writeInterval = writeInterval;
  this.threadFactory = threadFactory;
  this.metricRegistry = metricRegistry;
  this.writeQueue = writeQueue;
  this.metricExporter = new MetricExporter(writeQueue, metricWriter, threadFactory);
}
 
Example 16
/**
 * Creates the AST serializer executor service used for in-memory serialization of split functions' ASTs.
 * It is created with an unbounded queue (so it can queue any number of pending tasks). Its core and max
 * threads is the same, but they are all allowed to time out so when there's no work, they can all go
 * away. The threads will be daemons, and they will time out if idle for a minute. Their priority is also
 * slightly lower than normal priority as we'd prefer the CPU to keep running the program; serializing
 * split function is a memory conservation measure (it allows us to release the AST), it can wait a bit.
 * @return an executor service with above described characteristics.
 */
private static ExecutorService createAstSerializerExecutorService() {
    final int threads = Math.max(1, Options.getIntProperty("nashorn.serialize.threads", Runtime.getRuntime().availableProcessors() / 2));
    final ThreadPoolExecutor service = new ThreadPoolExecutor(threads, threads, 1L, TimeUnit.MINUTES, new LinkedBlockingDeque<Runnable>(),
            new ThreadFactory() {
                @Override
                public Thread newThread(final Runnable r) {
                    final Thread t = new Thread(r, "Nashorn AST Serializer");
                    t.setDaemon(true);
                    t.setPriority(Thread.NORM_PRIORITY - 1);
                    return t;
                }
            });
    service.allowCoreThreadTimeOut(true);
    return service;
}
 
Example 17
Source Project: hadoop   Source File: AsyncDiskService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a AsyncDiskServices with a set of volumes (specified by their
 * root directories).
 * 
 * The AsyncDiskServices uses one ThreadPool per volume to do the async
 * disk operations.
 * 
 * @param volumes The roots of the file system volumes.
 */
public AsyncDiskService(String[] volumes) {
  
  threadFactory = new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
      return new Thread(threadGroup, r);
    }
  };
  
  // Create one ThreadPool per volume
  for (int v = 0 ; v < volumes.length; v++) {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(
        CORE_THREADS_PER_VOLUME, MAXIMUM_THREADS_PER_VOLUME, 
        THREADS_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, 
        new LinkedBlockingQueue<Runnable>(), threadFactory);

    // This can reduce the number of running threads
    executor.allowCoreThreadTimeOut(true);
    executors.put(volumes[v], executor);
  }
  
}
 
Example 18
@Test
@SuppressWarnings("serial")
public void testShutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
	final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);

	ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
		@Override
		protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
			return executor;
		}
	};
	factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
		new NoOpScheduledExecutorTask()
	});
	factory.setWaitForTasksToCompleteOnShutdown(true);
	factory.afterPropertiesSet();
	factory.destroy();

	verify(executor).shutdown();
}
 
Example 19
@Default
default EventExecutorGroup executor() {
  Logger logger = LoggerFactory.getLogger("imap-executor");
  ThreadFactory threadFactory = new ThreadFactoryBuilder()
      .setDaemon(true)
      .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on thread {}", t.getName(), e))
      .setNameFormat("imap-executor-%d")
      .build();

  int nThreads = Runtime.getRuntime().availableProcessors() * 2;
  return new DefaultEventExecutorGroup(nThreads, threadFactory);
}
 
Example 20
Source Project: DDMQ   Source File: NodeManager.java    License: Apache License 2.0 5 votes vote down vote up
private void initScheduler() {
    restoreFromCooldownScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "RestoreFromCooldownScheduler");
        }
    });

    restoreFromCooldownScheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            restoreFromCooldown(null);
        }
    }, 2, 2, TimeUnit.SECONDS);
}
 
Example 21
@Override
protected ExecutorService initializeExecutor(
		ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

	ScheduledExecutorService executor =
			createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);

	if (this.removeOnCancelPolicy) {
		if (executor instanceof ScheduledThreadPoolExecutor) {
			((ScheduledThreadPoolExecutor) executor).setRemoveOnCancelPolicy(true);
		}
		else {
			logger.debug("Could not apply remove-on-cancel policy - not a ScheduledThreadPoolExecutor");
		}
	}

	// Register specified ScheduledExecutorTasks, if necessary.
	if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
		registerTasks(this.scheduledExecutorTasks, executor);
	}

	// Wrap executor with an unconfigurable decorator.
	this.exposedExecutor = (this.exposeUnconfigurableExecutor ?
			Executors.unconfigurableScheduledExecutorService(executor) : executor);

	return executor;
}
 
Example 22
Source Project: eagle   Source File: UtilityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static ThreadPoolExecutor createThreadPoolExecutor(final int queueSize, final String threadName, ThreadFactory threadFactory, final RejectedExecutionHandler policy) {
    if (threadFactory == null) {
        threadFactory = new DefaultThreadFactory(threadName, true);
    }

    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(queueSize);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 5, SECONDS, queue, threadFactory, policy);
    executor.allowCoreThreadTimeOut(true);
    return executor;
}
 
Example 23
Source Project: r2cloud   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
public static void shutdown(ScheduledExecutorService executor, long timeoutMillis) {
	if (executor == null) {
		return;
	}
	executor.shutdownNow();
	boolean cleanlyTerminated;
	try {
		cleanlyTerminated = executor.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS);
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
		cleanlyTerminated = executor.isTerminated();
	}
	if (!cleanlyTerminated) {
		String threadpoolName;
		if (executor instanceof ScheduledThreadPoolExecutor) {
			ThreadFactory factory = ((ScheduledThreadPoolExecutor) executor).getThreadFactory();
			if (factory instanceof NamingThreadFactory) {
				NamingThreadFactory namingFactory = (NamingThreadFactory) factory;
				threadpoolName = namingFactory.getPrefix();
			} else {
				threadpoolName = "unknown[" + factory.getClass().getSimpleName() + "]";
			}
		} else {
			threadpoolName = "unknown[" + executor.getClass().getSimpleName() + "]";
		}
		LOG.error("executor did not terminate in the specified time: {}", threadpoolName);
	}
}
 
Example 24
Source Project: grpc-nebula-java   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public EventLoopGroup create() {
  // Use Netty's DefaultThreadFactory in order to get the benefit of FastThreadLocal.
  boolean useDaemonThreads = true;
  ThreadFactory threadFactory = new DefaultThreadFactory(name, useDaemonThreads);
  int parallelism = numEventLoops == 0
      ? Runtime.getRuntime().availableProcessors() * 2 : numEventLoops;
  return new NioEventLoopGroup(parallelism, threadFactory);
}
 
Example 25
Source Project: sailfish-core   Source File: ReportServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {

	super.init(config);

	ThreadFactory threadFactory = new ThreadFactoryBuilder()
	        .setNameFormat(ReportServlet.class.getSimpleName() + "-%d")
	        .setDaemon(true)
	        .build();
	this.executor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), threadFactory);

}
 
Example 26
Source Project: oxygen   Source File: ThreadUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 默认全局线程工厂
 *
 * @return ThreadFactory
 */
public synchronized ThreadFactory defaultThreadFactory() {
  if (threadFactory == null) {
    threadFactory = new ThreadFactoryBuilder().setDaemon(true).setPriority(Thread.NORM_PRIORITY)
        .setNameFormat("def-pool-%d").build();
  }
  return threadFactory;
}
 
Example 27
/**
 * getThreadFactory returns factory in constructor if not set
 */
public void testGetThreadFactory() {
    final ThreadFactory threadFactory = new SimpleThreadFactory();
    final CustomExecutor p = new CustomExecutor(1, threadFactory);
    try (PoolCleaner cleaner = cleaner(p)) {
        assertSame(threadFactory, p.getThreadFactory());
    }
}
 
Example 28
Source Project: markdown-image-kit   Source File: SDKProgressPublisher.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new single threaded executor service for performing the
 * callbacks.
 */
private static ExecutorService createNewExecutorService() {
    return Executors.newSingleThreadExecutor(new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("java-sdk-progress-listener-callback-thread");
            t.setDaemon(true);
            return t;
        }
    });
}
 
Example 29
Source Project: eagle   Source File: StandardThreadExecutor.java    License: Apache License 2.0 5 votes vote down vote up
public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit,
        int queueCapacity, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
    super(coreThreads, maxThreads, keepAliveTime, unit, new ExecutorQueue(), threadFactory, handler);
    ((ExecutorQueue) getQueue()).setStandardThreadExecutor(this);

    submittedTasksCount = new AtomicInteger(0);

    // 最大并发任务限制: 队列buffer数 + 最大线程数
    maxSubmittedTaskCount = queueCapacity + maxThreads;
}
 
Example 30
@Test
public void customFactoryIsUsed() throws Exception {
    ThreadFactory threadFactory = spy(new CustomThreadFactory());
    SdkAsyncHttpClient customClient =
        NettyNioAsyncHttpClient.builder()
                               .eventLoopGroupBuilder(SdkEventLoopGroup.builder()
                                                                       .threadFactory(threadFactory))
                               .build();

    makeSimpleRequest(customClient);
    customClient.close();

    Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any());
}