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

The following are Jave code examples for showing how to use defaultThreadFactory() of the java.util.concurrent.Executors class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: monarch   File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java   View Source Code Vote up 6 votes
@Test
public void testShutdownDelayedTasks() throws InterruptedException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());
  ex.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  ex.schedule(new Runnable() {
    public void run() {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  }, 5000, TimeUnit.MILLISECONDS);
  ex.shutdown();
  long start = System.nanoTime();
  assertTrue(ex.awaitTermination(30, TimeUnit.SECONDS));
  long elapsed = System.nanoTime() - start;
  assertTrue("Shutdown should not have waited. Waited " + TimeUnit.NANOSECONDS.toMillis(elapsed),
      TimeUnit.SECONDS.toNanos(2) > elapsed);
}
 
Example 2
Project: monarch   File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java   View Source Code Vote up 6 votes
@Test
public void testRepeatedExecution() throws InterruptedException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());

  final AtomicInteger counter = new AtomicInteger();
  Runnable run = new Runnable() {
    public void run() {
      counter.incrementAndGet();
    }
  };
  ScheduledFuture f = ex.scheduleAtFixedRate(run, 0, 1, TimeUnit.SECONDS);
  Awaitility.await().atMost(30, TimeUnit.SECONDS)
      .until(() -> assertEquals("Task was not executed repeatedly", true, counter.get() > 1));
  Awaitility.await().atMost(30, TimeUnit.SECONDS)
      .until(() -> assertEquals("The task could not be cancelled", true, f.cancel(true)));
  Awaitility.await().atMost(30, TimeUnit.SECONDS)
      .until(() -> assertEquals("Task was not cancelled within 30 sec", true, f.isCancelled()));
  int oldValue = counter.get();
  Thread.sleep(5000);
  assertEquals("Task was not cancelled", oldValue, counter.get());
}
 
Example 3
Project: XinFramework   File: UploadThreadPool.java   View Source Code Vote up 5 votes
public XExecutor getExecutor() {
    if (executor == null) {
        synchronized (UploadThreadPool.class) {
            if (executor == null) {
                executor = new XExecutor(corePoolSize, MAX_IMUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, //
                                         new PriorityBlockingQueue<Runnable>(),   //无限容量的缓冲队列
                                         Executors.defaultThreadFactory(),        //线程创建工厂
                                         new ThreadPoolExecutor.AbortPolicy());   //继续超出上限的策略,阻止
            }
        }
    }
    return executor;
}
 
Example 4
Project: NeoSocket   File: Communi.java   View Source Code Vote up 5 votes
public ThreadPoolExecutor create() {
    // RejectedExecutionHandler 拒绝策略
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    /*
     * 参数1: 设置核心池大小
     * 参数2: 设置线程池最大能接受多少线程
     * 参数3: 当前线程数大于核心池大小、小于最大能接受线程时,超出核心池大小的线程数的生命周期
     * 参数4: 设置生命周期时间单位,秒
     * 参数5: 设置线程池缓存队列的排队策略为FIFO,并且指定缓存队列大小为2
     * 参数6: 线程工厂
     */
    return new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2), threadFactory);
}
 
Example 5
Project: Coder   File: UThread.java   View Source Code Vote up 5 votes
private TreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
    exec = new ThreadPoolExecutor(
            corePoolSize,// 核心线程数
            maximumPoolSize,// 最大线程数
            keepAliveTime,//闲置线程存活时间
            TimeUnit.SECONDS, // 时间单位
            new LinkedBlockingDeque<Runnable>(), // 线程队列
            Executors.defaultThreadFactory(), // 线程工厂
            new ThreadPoolExecutor.AbortPolicy() // 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
    );
    scheduleExec = Executors.newScheduledThreadPool(corePoolSize);
}
 
Example 6
Project: monarch   File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java   View Source Code Vote up 5 votes
@Category(FlakyTest.class) // GEODE-1138: time sensitive, thread sleeps, expiration
@Test
public void testConcurrentExecutionAndExpiration()
    throws InterruptedException, ExecutionException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());

  Runnable waitForABit = new Runnable() {
    public void run() {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  };

  Future[] futures = new Future[50];
  for (int i = 0; i < 50; i++) {
    futures[i] = ex.submit(waitForABit);
  }
  long start = System.nanoTime();

  for (int i = 0; i < 50; i++) {
    futures[i].get();
  }
  long end = System.nanoTime();

  assertTrue("Tasks executed in parallel", TimeUnit.NANOSECONDS.toSeconds(end - start) < 50);

  assertEquals(50, ex.getLargestPoolSize());

  // now make sure we expire back down.
  Thread.sleep(5000);
  assertEquals(1, ex.getPoolSize());
}
 
Example 7
Project: android-downloader   File: DownloadPool.java   View Source Code Vote up 5 votes
protected synchronized static void createPool() {
    BlockingQueue<Runnable> workers = new LinkedBlockingQueue<>();
    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
    mDownloadPool = new DownloadPool(
            corePoolSize,
            maxPoolSize,
            keepAliveTime,
            TimeUnit.MILLISECONDS,
            workers,
            Executors.defaultThreadFactory(),
            handler);
}
 
Example 8
Project: micrometer   File: NewRelicMeterRegistry.java   View Source Code Vote up 4 votes
public NewRelicMeterRegistry(NewRelicConfig config, Clock clock) {
    this(config, clock, Executors.defaultThreadFactory());
}
 
Example 9
Project: util4j   File: QueuesExecutorService.java   View Source Code Vote up 4 votes
protected QueuesExecutorService(int corePoolSize, int maximumPoolSize,
	Queue<Runnable> bossQueue,IndexQueueGroupManager indexQM,KeyQueueGroupManager keyQM,WaitConditionStrategy waitConditionStrategy) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),waitConditionStrategy,
    		bossQueue,indexQM,keyQM,new DirectExecutor());
}
 
Example 10
Project: util4j   File: SingleThreadTaskQueueExecutor_CountDownLatch.java   View Source Code Vote up 4 votes
public SingleThreadTaskQueueExecutor_CountDownLatch(String queueName) {
	this(queueName,Executors.defaultThreadFactory());
}
 
Example 11
Project: util4j   File: DefaultQueueGroupExecutor.java   View Source Code Vote up 4 votes
protected DefaultQueueGroupExecutor(int corePoolSize, int maximumPoolSize,
	Queue<Runnable> bossQueue,IndexQueueGroupManager indexQM,KeyQueueGroupManager keyQM) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),DEFAULT_waitConditionStrategy,
    		bossQueue,indexQM,keyQM,new DirectExecutor());
}
 
Example 12
Project: java-monitoring-client-library   File: SheepCounterExample.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
  if (args.length < 1) {
    System.err.println("Missing required project argument");
    System.err.printf(
        "Usage: java %s gcp-project-id [verbose]\n", SheepCounterExample.class.getName());
    return;
  }
  String project = args[0];

  // Turn up the logging verbosity
  if (args.length > 1) {
    Logger log = LogManager.getLogManager().getLogger("");
    log.setLevel(Level.ALL);
    for (Handler h : log.getHandlers()) {
      h.setLevel(Level.ALL);
    }
  }

  // Create a sample resource. In this case, a GCE Instance.
  // See https://cloud.google.com/monitoring/api/resources for a list of resource types.
  MonitoredResource monitoredResource =
      new MonitoredResource()
          .setType("gce_instance")
          .setLabels(
              ImmutableMap.of(
                  "instance_id", "test-instance",
                  "zone", "us-central1-f"));

  // Set up the Metrics infrastructure.
  MetricWriter stackdriverWriter =
      new StackdriverWriter(
          createAuthorizedMonitoringClient(),
          project,
          monitoredResource,
          STACKDRIVER_MAX_QPS,
          STACKDRIVER_MAX_POINTS_PER_REQUEST);
  final MetricReporter reporter =
      new MetricReporter(
          stackdriverWriter, METRICS_REPORTING_INTERVAL, Executors.defaultThreadFactory());
  reporter.startAsync().awaitRunning();

  // Set up a handler to stop sleeping on SIGINT.
  Runtime.getRuntime()
      .addShutdownHook(
          new Thread(
              () -> {
                reporter.stopAsync().awaitTerminated();
                // Allow the LogManager to cleanup the loggers.
                DelayedShutdownLogManager.resetFinally();
              }));

  System.err.println("Send SIGINT (Ctrl+C) to stop sleeping.");
  while (true) {
    // Count some Googley sheep.
    int colorIndex = new Random().nextInt(SHEEP_COLORS.size());
    int speciesIndex = new Random().nextInt(SHEEP_SPECIES.size());
    sheepCounter.incrementBy(1, SHEEP_COLORS.get(colorIndex), SHEEP_SPECIES.get(speciesIndex));
    sheepFluffiness.record(
        new Random().nextDouble() * 200,
        SHEEP_COLORS.get(colorIndex),
        SHEEP_SPECIES.get(speciesIndex));
    isSleeping.set(true);

    logger.info("zzz...");
    Thread.sleep(5000);
  }
}
 
Example 13
Project: util4j   File: AbstractTaskQueuesExecutor.java   View Source Code Vote up 4 votes
public AbstractTaskQueuesExecutor() {
	this(Executors.defaultThreadFactory());
}
 
Example 14
Project: util4j   File: ThreadPoolTaskQueuesExecutor.java   View Source Code Vote up 4 votes
public ThreadPoolTaskQueuesExecutor(int corePoolSize, int maximumPoolSize,
		WaitConditionStrategy waitConditionStrategy) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, Executors.defaultThreadFactory(),waitConditionStrategy);
}
 
Example 15
Project: guava-mock   File: ThreadFactoryBuilder.java   View Source Code Vote up 4 votes
private static ThreadFactory build(ThreadFactoryBuilder builder) {
  final String nameFormat = builder.nameFormat;
  final Boolean daemon = builder.daemon;
  final Integer priority = builder.priority;
  final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler;
  final ThreadFactory backingThreadFactory =
      (builder.backingThreadFactory != null)
          ? builder.backingThreadFactory
          : Executors.defaultThreadFactory();
  final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
  return new ThreadFactory() {
    @Override
    public Thread newThread(Runnable runnable) {
      Thread thread = backingThreadFactory.newThread(runnable);
      if (nameFormat != null) {
        thread.setName(format(nameFormat, count.getAndIncrement()));
      }
      if (daemon != null) {
        thread.setDaemon(daemon);
      }
      if (priority != null) {
        thread.setPriority(priority);
      }
      if (uncaughtExceptionHandler != null) {
        thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
      }
      return thread;
    }
  };
}
 
Example 16
Project: Requester   File: ConnectionThreadPool.java   View Source Code Vote up 4 votes
public  void init (){

        RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();

        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        executorPool = new ThreadPoolExecutor(CORE, MAX, TIMEOUT, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100),
                threadFactory, rejectionHandler);

        monitor = new MyMonitorThread(executorPool, 15);
        Thread monitorThread = new Thread(monitor);
        monitorThread.start();

        executorPool.prestartAllCoreThreads();

    }
 
Example 17
Project: cakes   File: Main.java   View Source Code Vote up 3 votes
public static void main(String[] args) {
    ThreadFactory threadFactory = Executors.defaultThreadFactory();

    Disruptor<UserEvent> disruptor = new Disruptor<>(new UserEventFactory(), 1024, threadFactory, ProducerType.SINGLE, new YieldingWaitStrategy());

    disruptor.handleEventsWith(new UserEventConsumer());

    disruptor.start();

    new UserEventProducer(disruptor.getRingBuffer()).doProcess();

    disruptor.shutdown();
}
 
Example 18
Project: util4j   File: FixedThreadPoolBlockingQueuesExecutor.java   View Source Code Vote up 2 votes
/**
 * Creates a default ThreadPool, with default values :
 * - keepAlive set to 30 seconds
 * - A default ThreadFactory
 * - All events are accepted
 *
 * @param corePoolSize The initial pool sizePoolSize
 * @param maximumPoolSize The maximum pool size
 */
public FixedThreadPoolBlockingQueuesExecutor(int corePoolSize, int maximumPoolSize) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, Executors.defaultThreadFactory());
}
 
Example 19
Project: uavstack   File: QueueWorkerThreadPoolExecutor.java   View Source Code Vote up 2 votes
/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial parameters and default thread factory and
 * rejected execution handler. It may be more convenient to use one of the {@link Executors} factory methods instead
 * of this general purpose constructor.
 *
 * @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.
 * @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} is null
 */
public QueueWorkerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(),
            defaultHandler);
}
 
Example 20
Project: neoscada   File: OrderedThreadPoolExecutor.java   View Source Code Vote up 2 votes
/**
 * Creates a default ThreadPool, with default values :
 * - minimum pool size is 0
 * - maximum pool size is 16
 * - keepAlive set to 30 seconds
 * - A default ThreadFactory
 * - All events are accepted
 */
public OrderedThreadPoolExecutor() {
    this(DEFAULT_INITIAL_THREAD_POOL_SIZE, DEFAULT_MAX_THREAD_POOL, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, Executors
            .defaultThreadFactory(), null);
}