Java Code Examples for java.util.concurrent.Executors#defaultThreadFactory()

The following examples show how to use java.util.concurrent.Executors#defaultThreadFactory() . 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: ThreadPoolManager.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ThreadPoolModel(final int core, final int max,
                        final long keepAliveTime, final TimeUnit keepAliveTimeUnit,
                        final BlockingQueue<Runnable> workQueue,
                        final ThreadFactory threadFactory,
                        final RejectedExecutionHandler handler,
                        final long shutdownTime, final TimeUnit shutdownTimeUnit) {
    this.core = core;
    this.max = max;
    this.keepAliveTime = keepAliveTime;
    this.keepAliveTimeUnit = keepAliveTimeUnit == null ? MILLISECONDS : keepAliveTimeUnit;
    this.shutdownTime = shutdownTime;
    this.shutdownTimeUnit = shutdownTimeUnit == null ? MILLISECONDS : shutdownTimeUnit;
    this.workQueue = workQueue == null ? new LinkedBlockingDeque<>() : workQueue;
    this.threadFactory = threadFactory == null ? Executors.defaultThreadFactory() : threadFactory;
    this.handler = handler == null ? new ThreadPoolExecutor.AbortPolicy() : handler;
}
 
Example 2
Source File: ThreadPoolManager.java    From LLApp with Apache License 2.0 6 votes vote down vote up
private ThreadPoolManager() {
    /**
     * 给corePoolSize赋值:当前设备可用处理器核心数*2 + 1,能够让cpu的效率得到最大程度执行(有研究论证的)
     */
    corePoolSize = Runtime.getRuntime().availableProcessors()*2+1;
    maximumPoolSize = corePoolSize; //虽然maximumPoolSize用不到,但是需要赋值,否则报错
    executor = new ThreadPoolExecutor(
            corePoolSize, //当某个核心任务执行完毕,会依次从缓冲队列中取出等待任务
            maximumPoolSize, //5,先corePoolSize,然后new LinkedBlockingQueue<Runnable>(),然后maximumPoolSize,但是它的数量是包含了corePoolSize的
            keepAliveTime, //表示的是maximumPoolSize当中等待任务的存活时间
            unit,
            new LinkedBlockingQueue<Runnable>(), //缓冲队列,用于存放等待任务,Linked的先进先出
            Executors.defaultThreadFactory(), //创建线程的工厂
            new ThreadPoolExecutor.AbortPolicy() //用来对超出maximumPoolSize的任务的处理策略
    );
}
 
Example 3
Source File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testDelayedExcecution() throws InterruptedException, ExecutionException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(
      50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
  long start = CFactory.nanoTime();
  Future f = ex.schedule(new Runnable() { public void run() {}}, 10, TimeUnit.SECONDS);
  f.get();
  long end = CFactory.nanoTime();
  assertTrue("Execution was not delayed 10 seconds, only " + (end - start), 
      TimeUnit.SECONDS.toNanos(10) <= end - start + SLOP); 
}
 
Example 4
Source File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testConcurrentRepeatedTasks() throws InterruptedException, ExecutionException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(
      50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
  
  final AI counter = CFactory.createAI(); 
  Runnable waitForABit = new Runnable() {
    public void run() {
      try {
        counter.incrementAndGet();
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  };
  
  Future[] futures = new Future[50];
  for(int i = 0; i < 50; i++) {
    futures[i] = ex.scheduleAtFixedRate(waitForABit,0, 1, TimeUnit.SECONDS);
  }
  
  Thread.sleep(10000);
  
  for(int i = 0; i < 50; i++) {
    futures[i].cancel(true);
  }
  
  assertTrue("Tasks did not execute in parallel. Expected more than 300 executions, got " + counter.get(), counter.get() > 300);
  
  assertEquals(50, ex.getLargestPoolSize());
  
  //now make sure we expire back down.
  Thread.sleep(5000);
  assertEquals(1, ex.getPoolSize());
}
 
Example 5
Source File: AbstractSourceView.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void internalComputeAndSetInput(final IWorkbenchPartSelection workbenchPartSelection, boolean forceSelection) {
	if (!forceSelection && isIgnored(workbenchPartSelection)) {
		return;
	}
	this.workbenchPartSelection = workbenchPartSelection;
	final int currentCount = ++computeCount;
	ThreadFactory threadFactory = Executors.defaultThreadFactory();
	Thread thread = threadFactory.newThread(new Runnable() {
		@Override
		public void run() {
			if (currentCount != computeCount) {
				return;
			}
			final String input = computeInput(workbenchPartSelection);
			if (input == null) {
				return;
			}
			Display display = getDisplay();
			if (display == null) {
				return;
			}
			runAsyncInDisplayThread(new Runnable() {
				@Override
				public void run() {
					if (computeCount != currentCount || getViewSite().getShell().isDisposed()) {
						return;
					}
					String description = computeDescription(workbenchPartSelection);
					setContentDescription(description);
					setInput(input);
					selectAndReveal(workbenchPartSelection);
				}

			});
		}
	});
	thread.setDaemon(true);
	thread.setPriority(Thread.MIN_PRIORITY);
	thread.start();
}
 
Example 6
Source File: IdlingScheduledThreadPoolExecutorTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  initMocks(this);
  this.executor =
      new IdlingScheduledThreadPoolExecutor("resource", 2, Executors.defaultThreadFactory());
  this.executor.registerIdleTransitionCallback(mockCallback);
}
 
Example 7
Source File: ImportDispatcher.java    From proarc with GNU General Public License v3.0 4 votes vote down vote up
public ImportDispatcherThreadFactory() {
    factory = Executors.defaultThreadFactory();
}
 
Example 8
Source File: NioUdtMessageRendezvousChannelTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * verify basic echo message rendezvous
 *
 * FIXME: Re-enable after making it pass on Windows without unncessary tight loop.
 *        https://github.com/netty/netty/issues/2853
 */
@Test(timeout = 10 * 1000)
@Ignore
public void basicEcho() throws Exception {

    final int messageSize = 64 * 1024;
    final int transferLimit = messageSize * 16;

    final Meter rate1 = Metrics.newMeter(
            NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);

    final Meter rate2 = Metrics.newMeter(
            NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);

    final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
    final InetSocketAddress addr2 = UnitHelp.localSocketAddress();

    final EchoMessageHandler handler1 = new EchoMessageHandler(rate1, messageSize);
    final EchoMessageHandler handler2 = new EchoMessageHandler(rate2, messageSize);

    final NioEventLoopGroup group1 = new NioEventLoopGroup(
            1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup group2 = new NioEventLoopGroup(
            1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);

    final Bootstrap boot1 = new Bootstrap();
    boot1.group(group1)
         .channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
         .localAddress(addr1).remoteAddress(addr2).handler(handler1);

    final Bootstrap boot2 = new Bootstrap();
    boot2.group(group2)
         .channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
         .localAddress(addr2).remoteAddress(addr1).handler(handler2);

    final ChannelFuture connectFuture1 = boot1.connect();
    final ChannelFuture connectFuture2 = boot2.connect();

    while (handler1.meter().count() < transferLimit
            && handler2.meter().count() < transferLimit) {

        log.info("progress : {} {}", handler1.meter().count(), handler2
                .meter().count());

        Thread.sleep(1000);
    }

    connectFuture1.channel().close().sync();
    connectFuture2.channel().close().sync();

    log.info("handler1 : {}", handler1.meter().count());
    log.info("handler2 : {}", handler2.meter().count());

    assertTrue(handler1.meter().count() >= transferLimit);
    assertTrue(handler2.meter().count() >= transferLimit);

    assertEquals(handler1.meter().count(), handler2.meter().count());

    group1.shutdownGracefully();
    group2.shutdownGracefully();

    group1.terminationFuture().sync();
    group2.terminationFuture().sync();
}
 
Example 9
Source File: HuaweiThreadManager.java    From MixPush with Apache License 2.0 4 votes vote down vote up
@Override
protected ThreadFactory getThreadFactory() {
    return Executors.defaultThreadFactory();
}
 
Example 10
Source File: DefaultQueueGroupExecutor.java    From util4j with Apache License 2.0 4 votes vote down vote up
protected DefaultQueueGroupExecutor(int corePoolSize, int maximumPoolSize,
	Queue<Runnable> bossQueue,QueueGroupManager queueMananger,WaitConditionStrategy waitConditionStrategy) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),waitConditionStrategy,
    		bossQueue,queueMananger,new DirectExecutor());
}
 
Example 11
Source File: DefaultQueueGroupExecutor.java    From util4j with Apache License 2.0 4 votes vote down vote up
protected DefaultQueueGroupExecutor(int corePoolSize, int maximumPoolSize,Queue<Runnable> bossQueue) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),default_waitConditionStrategy(),
    		bossQueue,default_QueueGroupManager(),null);
}
 
Example 12
Source File: BlynkTPFactory.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
private BlynkTPFactory(String name) {
    this.defaultThreadFactory = Executors.defaultThreadFactory();
    this.name = name;
}
 
Example 13
Source File: PriorityThreadPoolExecutor.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
public PriorityThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit)
{
	this(corePoolSize, maximumPoolSize, keepAliveTime, unit, Executors.defaultThreadFactory(), defaultHandler);
}
 
Example 14
Source File: DaemonThreadFactory.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Uses {@link Executors#defaultThreadFactory()} as the delegate.
 */
public DaemonThreadFactory() {
    
    this( Executors.defaultThreadFactory(), null/*basename*/ );
    
}
 
Example 15
Source File: NamingThreadFactory.java    From GPT with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new factory that delegates to the default thread factory for
 * thread creation, then uses {@code format} to construct a name for the new
 * thread.
 *
 * @param prefix 线程名前缀
 */
public NamingThreadFactory(String prefix) {
    this(prefix, Executors.defaultThreadFactory());
}
 
Example 16
Source File: HashedWheelTimer.java    From netty4.0.27Learn with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new timer with the default thread factory
 * ({@link Executors#defaultThreadFactory()}), default tick duration, and
 * default number of ticks per wheel.
 */
public HashedWheelTimer() {
    this(Executors.defaultThreadFactory());
}
 
Example 17
Source File: HashedWheelTimer.java    From sofa-jraft with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new timer with the default thread factory
 * ({@link Executors#defaultThreadFactory()}), default tick duration, and
 * default number of ticks per wheel.
 */
public HashedWheelTimer() {
    this(Executors.defaultThreadFactory());
}
 
Example 18
Source File: HashedWheelTimer.java    From android-netty with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new timer with the default thread factory
 * ({@link Executors#defaultThreadFactory()}), default tick duration, and
 * default number of ticks per wheel.
 */
public HashedWheelTimer() {
    this(Executors.defaultThreadFactory());
}
 
Example 19
Source File: HashedWheelTimer.java    From netty-4.1.22 with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new timer with the default thread factory
 * ({@link Executors#defaultThreadFactory()}).使用默认线程工厂(Executors.defaultThreadFactory())创建一个新的计时器。
 *
 * @param tickDuration   the duration between tick
 * @param unit           the time unit of the {@code tickDuration}
 * @param ticksPerWheel  the size of the wheel
 * @throws NullPointerException     if {@code unit} is {@code null}
 * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0
 */
public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) {
    this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel);
}
 
Example 20
Source File: QueueWorkerThreadPoolExecutor.java    From uavstack with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial parameters and default thread factory.
 *
 * @param corePoolSize
 *            the number of threads to keep in the pool, even if they are idle, unless
 *            {@code allowCoreThreadTimeOut} is set
 * @param maximumPoolSize
 *            the maximum number of threads to allow in the pool
 * @param keepAliveTime
 *            when the number of threads is greater than the core, this is the maximum time that excess idle threads
 *            will wait for new tasks before terminating.
 * @param unit
 *            the time unit for the {@code keepAliveTime} argument
 * @param workQueue
 *            the queue to use for holding tasks before they are executed. This queue will hold only the
 *            {@code Runnable} tasks submitted by the {@code execute} method.
 * @param handler
 *            the handler to use when execution is blocked because the thread bounds and queue capacities are
 *            reached
 * @throws IllegalArgumentException
 *             if one of the following holds:<br>
 *             {@code corePoolSize < 0}<br>
 *             {@code keepAliveTime < 0}<br>
 *             {@code maximumPoolSize <= 0}<br>
 *             {@code maximumPoolSize < corePoolSize}
 * @throws NullPointerException
 *             if {@code workQueue} or {@code handler} is null
 */
public QueueWorkerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        BlockingQueue<Runnable> workQueue, QueueWorkerRejectedExecutionHandler handler) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler);
}