java.util.concurrent.ArrayBlockingQueue Java Examples

The following examples show how to use java.util.concurrent.ArrayBlockingQueue. 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: ControlledProgressTracker.java    From twister2 with Apache License 2.0 6 votes vote down vote up
public ControlledProgressTracker(List<IntArrayList> items) {
  if (items.size() == 0) {
    canProgress = false;
  } else {
    canProgress = true;
    this.progressItems = new ArrayList<>(items.size());
    for (int i = 0; i < items.size(); i++) {
      List<Integer> taskLists = items.get(i);
      Queue<Integer> progressQueue = new ArrayBlockingQueue<>(taskLists.size());
      progressQueue.addAll(taskLists);
      progressItems.add(progressQueue);
      for (int t : taskLists) {
        invertedItems.put(t, i);
      }
    }
  }
}
 
Example #2
Source File: ArrayBlockingQueueTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * offer transfers elements across Executor tasks
 */
public void testOfferInExecutor() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    q.add(one);
    q.add(two);
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(executor)) {
        executor.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                assertFalse(q.offer(three));
                threadsStarted.await();
                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
                assertEquals(0, q.remainingCapacity());
            }});

        executor.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                threadsStarted.await();
                assertEquals(0, q.remainingCapacity());
                assertSame(one, q.take());
            }});
    }
}
 
Example #3
Source File: LenientParsingTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnyExceptionWrappedInParameterException() {
    class App {
        @Option(names = "-queue", type = String.class, split = ",")
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
    }
    CommandLine cmd = new CommandLine(new App());
    cmd.getCommandSpec().parser().collectErrors(true);
    cmd.parseArgs("-queue", "a,b,c");

    ParseResult parseResult = cmd.getParseResult();
    assertTrue(parseResult.unmatched().isEmpty());
    assertEquals(1, parseResult.errors().size());

    assertTrue(parseResult.errors().get(0) instanceof ParameterException);
    assertTrue(parseResult.errors().get(0).getCause() instanceof NoSuchMethodException);

    assertEquals("NoSuchMethodException: java.util.concurrent.ArrayBlockingQueue.<init>() while processing argument at or before arg[1] 'a,b,c' in [-queue, a,b,c]: java.lang.NoSuchMethodException: java.util.concurrent.ArrayBlockingQueue.<init>()",
            parseResult.errors().get(0).getMessage());
    assertEquals("java.util.concurrent.ArrayBlockingQueue.<init>()", parseResult.errors().get(0).getCause().getMessage());
}
 
Example #4
Source File: ArrayBlockingQueueTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * drainTo empties full queue, unblocking a waiting put.
 */
public void testDrainToWithActivePut() throws InterruptedException {
    final ArrayBlockingQueue q = populatedQueue(SIZE);
    Thread t = new Thread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            q.put(new Integer(SIZE + 1));
        }});

    t.start();
    ArrayList l = new ArrayList();
    q.drainTo(l);
    assertTrue(l.size() >= SIZE);
    for (int i = 0; i < SIZE; ++i)
        assertEquals(l.get(i), new Integer(i));
    t.join();
    assertTrue(q.size() + l.size() >= SIZE);
}
 
Example #5
Source File: WhiteBox.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Interior removal of elements used by an iterator will cause it
 * to be untracked.
 */
public void interiorRemovalOfElementsUsedByIterator() {
    boolean fair = rnd.nextBoolean();
    int capacity = rnd.nextInt(10, 20);
    ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair);
    randomizePutIndex(q);
    q.add(0);
    for (int i = 1; i < 2 * capacity; i++) {
        q.add(i);
        Integer[] elts = { -1, -2, -3 };
        for (Integer elt : elts) q.add(elt);
        assertEquals(q.remove(), i - 1);
        Iterator it = q.iterator();
        assertEquals(it.next(), i);
        assertEquals(it.next(), elts[0]);
        Collections.shuffle(Arrays.asList(elts));
        assertTrue(q.remove(elts[0]));
        assertTrue(q.remove(elts[1]));
        assertEquals(trackedIterators(q), Collections.singletonList(it));
        assertTrue(q.remove(elts[2]));
        assertNull(itrs(q));
        assertEquals(it.next(), -2);
        assertIteratorExhausted(it);
        assertTrue(isDetached(it));
    }
}
 
Example #6
Source File: MasterFifoRpcScheduler.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
  LOG.info(
    "Using {} as call queue; handlerCount={}; maxQueueLength={}; rsReportHandlerCount={}; "
        + "rsReportMaxQueueLength={}",
    this.getClass().getSimpleName(), handlerCount, maxQueueLength, rsReportHandlerCount,
    rsRsreportMaxQueueLength);
  this.executor = new ThreadPoolExecutor(handlerCount, handlerCount, 60, TimeUnit.SECONDS,
      new ArrayBlockingQueue<Runnable>(maxQueueLength),
      Threads.newDaemonThreadFactory("MasterFifoRpcScheduler.call.handler"),
      new ThreadPoolExecutor.CallerRunsPolicy());
  this.rsReportExecutor = new ThreadPoolExecutor(rsReportHandlerCount, rsReportHandlerCount, 60,
      TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(rsRsreportMaxQueueLength),
      Threads.newDaemonThreadFactory("MasterFifoRpcScheduler.RSReport.handler"),
      new ThreadPoolExecutor.CallerRunsPolicy());
}
 
Example #7
Source File: TunnelServerTest.java    From tunnel with Apache License 2.0 6 votes vote down vote up
@Test
public void test_threadPool() {
    int total = 4;
    ThreadPoolExecutor executor = new ThreadPoolExecutor(total, total, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));

    for (int i = 0; i < total; i++) {
        executor.submit(new Task(i));
    }

    try {
        executor.awaitTermination(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        //
    }
    stopped = true;
    executor.shutdown();
}
 
Example #8
Source File: ParallelResourceLoader.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
public ParallelLoadOperation(final ResourceSet parent, final IProject project) {
  this.parent = parent;
  if (queueSize == -1) {
    this.resourceQueue = new LinkedBlockingQueue<Triple<URI, Resource, Throwable>>();
  } else if (queueSize == 0) {
    this.resourceQueue = new SynchronousQueue<Triple<URI, Resource, Throwable>>();
  } else {
    this.resourceQueue = new ArrayBlockingQueue<Triple<URI, Resource, Throwable>>(queueSize);
  }
  this.resourceSetProvider = new ThreadLocal<ResourceSet>() {
    @Override
    protected ResourceSet initialValue() {
      ResourceSet resourceSet = getResourceSetProvider().get(project);
      BuildPhases.setIndexing(resourceSet, BuildPhases.isIndexing(parent));
      DirectLinkingSourceLevelURIsAdapter.setSourceLevelUris(resourceSet, DirectLinkingSourceLevelURIsAdapter.findInstalledAdapter(parent).getSourceLevelURIs());
      resourceSet.getLoadOptions().putAll(parent.getLoadOptions());
      // we are not loading as part of a build
      resourceSet.getLoadOptions().remove(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE);
      resourceSet.setURIConverter(parent.getURIConverter());
      return resourceSet;
    }
  };
  this.executor = Executors.newFixedThreadPool(nThreads, new ThreadFactoryBuilder().setNameFormat("parallel-load-operation-%d").build()); //$NON-NLS-1$
  this.waitTime = getTimeout();
}
 
Example #9
Source File: ConsumeEWS.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession processSession) throws ProcessException {
    if(this.messageQueue == null){
        int fetchSize = context.getProperty(FETCH_SIZE).evaluateAttributeExpressions().asInteger();
        this.messageQueue = new ArrayBlockingQueue<>(fetchSize);
    }

    this.folderName = context.getProperty(FOLDER).getValue();

    Message emailMessage = this.receiveMessage(context);
    if (emailMessage != null) {
        this.transfer(emailMessage, context, processSession);
    } else {
        //No new messages found, yield the processor
        context.yield();
    }
}
 
Example #10
Source File: ConsumerCommitServiceImpl.java    From pmq with Apache License 2.0 6 votes vote down vote up
@Override
public void startBroker() {
	commitThreadSize = soaConfig.getCommitThreadSize();
	executorRun = new ThreadPoolExecutor(commitThreadSize + 1, commitThreadSize + 1, 10L, TimeUnit.SECONDS,
			new ArrayBlockingQueue<>(50), SoaThreadFactory.create("commit-run", Thread.MAX_PRIORITY - 1, true),
			new ThreadPoolExecutor.CallerRunsPolicy());
	soaConfig.registerChanged(new Runnable() {
		@Override
		public void run() {
			if (commitThreadSize != soaConfig.getCommitThreadSize()) {
				commitThreadSize = soaConfig.getCommitThreadSize();
				executorRun.setCorePoolSize(commitThreadSize + 1);
				executorRun.setMaximumPoolSize(commitThreadSize + 1);
			}

		}
	});
	executorRun.execute(() -> {
		commitOffset();
	});

}
 
Example #11
Source File: ProcessPoolOfficeManager.java    From kkFileView with Apache License 2.0 6 votes vote down vote up
public ProcessPoolOfficeManager(File officeHome, UnoUrl[] unoUrls, String[] runAsArgs, File templateProfileDir, File workDir,
          long retryTimeout, long taskQueueTimeout, long taskExecutionTimeout, int maxTasksPerProcess,
          ProcessManager processManager) {
this.taskQueueTimeout = taskQueueTimeout;
      pool = new ArrayBlockingQueue<PooledOfficeManager>(unoUrls.length);
      pooledManagers = new PooledOfficeManager[unoUrls.length];
      for (int i = 0; i < unoUrls.length; i++) {
          PooledOfficeManagerSettings settings = new PooledOfficeManagerSettings(unoUrls[i]);
          settings.setRunAsArgs(runAsArgs);
          settings.setTemplateProfileDir(templateProfileDir);
          settings.setWorkDir(workDir);
          settings.setOfficeHome(officeHome);
          settings.setRetryTimeout(retryTimeout);
          settings.setTaskExecutionTimeout(taskExecutionTimeout);
          settings.setMaxTasksPerProcess(maxTasksPerProcess);
          settings.setProcessManager(processManager);
          pooledManagers[i] = new PooledOfficeManager(settings);
      }
      logger.info("ProcessManager implementation is " + processManager.getClass().getSimpleName());
  }
 
Example #12
Source File: AbstractExecutorServiceTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * submit(callable).get() throws InterruptedException if interrupted
 */
public void testInterruptedSubmit() throws InterruptedException {
    final CountDownLatch submitted    = new CountDownLatch(1);
    final CountDownLatch quittingTime = new CountDownLatch(1);
    final Callable<Void> awaiter = new CheckedCallable<Void>() {
        public Void realCall() throws InterruptedException {
            assertTrue(quittingTime.await(2*LONG_DELAY_MS, MILLISECONDS));
            return null;
        }};
    final ExecutorService p
        = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
                                 new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p, quittingTime)) {
        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
            public void realRun() throws Exception {
                Future<Void> future = p.submit(awaiter);
                submitted.countDown();
                future.get();
            }});

        await(submitted);
        t.interrupt();
        awaitTermination(t);
    }
}
 
Example #13
Source File: MpmcBenchmark.java    From java-Kcp with Apache License 2.0 6 votes vote down vote up
@Setup(Level.Trial)
public void setUp() {
    switch (implementation) {
        case PARAM_UNSAFE:
            //queue = new MpmcArrayQueue<>(CAPACITY);
            break;
        case PARAM_AFU:
            //queue = new MpmcAtomicArrayQueue<>(CAPACITY);
            break;
        case PARAM_JDK:
            queue = new ArrayBlockingQueue<>(CAPACITY);
            break;
        default:
            throw new UnsupportedOperationException("Unsupported implementation " + implementation);
    }
}
 
Example #14
Source File: BackgroundLayoutLooperRule.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      ShadowLooper layoutLooper =
          Shadows.shadowOf(
              (Looper)
                  Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper"));
      mMessageQueue = new ArrayBlockingQueue<>(100);
      LayoutLooperThread layoutLooperThread = new LayoutLooperThread(layoutLooper, mMessageQueue);
      layoutLooperThread.start();
      try {
        base.evaluate();
      } finally {
        mMessageQueue.add(new Message(MessageType.QUIT));
      }
    }
  };
}
 
Example #15
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * getPoolSize increases, but doesn't overestimate, when threads
 * become active
 */
public void testGetPoolSize() throws InterruptedException {
    final CountDownLatch done = new CountDownLatch(1);
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p, done)) {
        assertEquals(0, p.getPoolSize());
        final CountDownLatch threadStarted = new CountDownLatch(1);
        p.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                threadStarted.countDown();
                assertEquals(1, p.getPoolSize());
                await(done);
            }});
        await(threadStarted);
        assertEquals(1, p.getPoolSize());
    }
}
 
Example #16
Source File: QueuedThreadPool.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
@Override
protected void doStart() throws Exception
{
    super.doStart();
    _threadsStarted.set(0);

    if (_jobs==null)
    {
        _jobs=_maxQueued>0 ?new ArrayBlockingQueue<Runnable>(_maxQueued)
            :new BlockingArrayQueue<Runnable>(_minThreads,_minThreads);
    }

    int threads=_threadsStarted.get();
    while (isRunning() && threads<_minThreads)
    {
        startThread(threads);
        threads=_threadsStarted.get();
    }
}
 
Example #17
Source File: MetricFetcher.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public MetricFetcher() {
    int cores = Runtime.getRuntime().availableProcessors() * 2;
    long keepAliveTime = 0;
    int queueSize = 2048;
    RejectedExecutionHandler handler = new DiscardPolicy();
    fetchService = new ThreadPoolExecutor(cores, cores,
        keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
        new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), handler);
    fetchWorker = new ThreadPoolExecutor(cores, cores,
        keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
        new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), handler);
    IOReactorConfig ioConfig = IOReactorConfig.custom()
        .setConnectTimeout(3000)
        .setSoTimeout(3000)
        .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2)
        .build();

    httpclient = HttpAsyncClients.custom()
        .setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            protected boolean isRedirectable(final String method) {
                return false;
            }
        }).setMaxConnTotal(4000)
        .setMaxConnPerRoute(1000)
        .setDefaultIOReactorConfig(ioConfig)
        .build();
    httpclient.start();
    start();
}
 
Example #18
Source File: BlockingQueueFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 向工厂中添加队列.
 * @param key 队列Key
 * @param queue 队列
 */
public void setQueue(final String key, final ArrayBlockingQueue<Object> queue) {
    if (getQueue(key) != null) {
        final BlockingQueue<Object> theQueue = getQueue(key);
        theQueue.addAll(queue);
    } else {
        queueMap.put(key, queue);
    }
}
 
Example #19
Source File: MqClient.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void doInit(MqConfig config) {
			if (!Util.isEmpty(config.getServerPort())) {
				if (config.getServerPort().indexOf('|') != -1) {
					mqContext.setConsumerName(String.format("%s|%s|%s%s", config.getIp(), PropUtil.getProcessId(),
							System.currentTimeMillis() % 10000, config.getServerPort()));
				} else {
					mqContext.setConsumerName(String.format("%s|%s|%s|%s", config.getIp(), PropUtil.getProcessId(),
							System.currentTimeMillis() % 10000, config.getServerPort()));
				}
			} else {
				mqContext.setConsumerName(String.format("%s|%s|%s", config.getIp(), PropUtil.getProcessId(),
						System.currentTimeMillis() % 10000));
			}
			if (mqContext.getMqResource() == null) {
				mqContext.setMqResource(getMqFactory().createMqResource(config.getUrl(), config.getReadTimeOut(),
						config.getReadTimeOut()));
			}
			mqContext.setConfig(config);
//			if (config.getAsynCapacity() < 2000) {
//				log.info("异步缓冲队列至少2000!");
//				config.setAsynCapacity(2000);
//			}
			msgsAsyn = new ArrayBlockingQueue<>(config.getAsynCapacity());

			mqBrokerUrlRefreshService = mqFactory.createMqBrokerUrlRefreshService(this);
			mqBrokerUrlRefreshService.start();
		}
 
Example #20
Source File: R090_UnicastProcessor.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void twoSubscribers() throws Exception {
    //given
    final UnicastProcessor<Long> proc = UnicastProcessor
            .create(
                    new ArrayBlockingQueue<>(10),
                    x -> log.warn("Dropped {}", x),
                    () -> {
                    });


    //when
    pushSomeEvents(proc, 0, 11);

    //then
    proc
            .subscribeOn(Schedulers.elastic())
            .subscribe(
                    x -> log.info("Got {}", x),
                    e -> log.error("Error", e));
    proc
            .subscribeOn(Schedulers.elastic())
            .subscribe(
                    x -> log.info("Got {}", x),
                    e -> log.error("Error", e));

    TimeUnit.SECONDS.sleep(1);
}
 
Example #21
Source File: ThreadPoolExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * awaitTermination on a non-shutdown pool times out
 */
public void testAwaitTermination_timesOut() throws InterruptedException {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        assertFalse(p.isTerminated());
        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
        assertFalse(p.awaitTermination(0L, NANOSECONDS));
        assertFalse(p.awaitTermination(0L, MILLISECONDS));
        long timeoutNanos = 999999L;
        long startTime = System.nanoTime();
        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
        assertFalse(p.isTerminated());
        startTime = System.nanoTime();
        long timeoutMillis = timeoutMillis();
        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
        assertFalse(p.isTerminated());
        try { p.shutdown(); } catch (SecurityException ok) { return; }
        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(p.isTerminated());
    }
}
 
Example #22
Source File: BufferingSpliterator.java    From streams with Apache License 2.0 5 votes vote down vote up
BufferingSpliterator(
        CompletionStrategy completionStrategy, Spliterator<F> futures, int maxParallelism) {
    this.completionStrategy = completionStrategy;
    checkArgument(maxParallelism > 0,
            "maxParallelism must be at least 1 (got %s)", new Object[] {maxParallelism});
    this.maxParallelism = maxParallelism;
    this.completed = new ArrayBlockingQueue<>(maxParallelism);
    this.notStarted = futures;
}
 
Example #23
Source File: ThreadPoolExecutorSubclassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * getCompletedTaskCount increases, but doesn't overestimate,
 * when tasks complete
 */
public void testGetCompletedTaskCount() throws InterruptedException {
    final ThreadPoolExecutor p =
        new CustomTPE(2, 2,
                      LONG_DELAY_MS, MILLISECONDS,
                      new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        final CountDownLatch threadStarted = new CountDownLatch(1);
        final CountDownLatch threadProceed = new CountDownLatch(1);
        final CountDownLatch threadDone = new CountDownLatch(1);
        assertEquals(0, p.getCompletedTaskCount());
        p.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                threadStarted.countDown();
                assertEquals(0, p.getCompletedTaskCount());
                threadProceed.await();
                threadDone.countDown();
            }});
        await(threadStarted);
        assertEquals(0, p.getCompletedTaskCount());
        threadProceed.countDown();
        threadDone.await();
        long startTime = System.nanoTime();
        while (p.getCompletedTaskCount() != 1) {
            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
                fail("timed out");
            Thread.yield();
        }
    }
}
 
Example #24
Source File: KQueuePort.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
KQueuePort(AsynchronousChannelProvider provider, ThreadPool pool)
    throws IOException
{
    super(provider, pool);

    // open kqueue
    this.kqfd = kqueue();

    // create socket pair for wakeup mechanism
    int[] sv = new int[2];
    try {
        socketpair(sv);

        // register one end with kqueue
        keventRegister(kqfd, sv[0], EVFILT_READ, EV_ADD);
    } catch (IOException x) {
        close0(kqfd);
        throw x;
    }
    this.sp = sv;

    // allocate the poll array
    this.address = allocatePollArray(MAX_KEVENTS_TO_POLL);

    // create the queue and offer the special event to ensure that the first
    // threads polls
    this.queue = new ArrayBlockingQueue<Event>(MAX_KEVENTS_TO_POLL);
    this.queue.offer(NEED_TO_POLL);
}
 
Example #25
Source File: EventManager.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * 
 */
private EventManager() {
    subscriberHolder = new ConcurrentHashMap<>();
    queueHolder = new ConcurrentHashMap<>();
    executor = new ThreadPoolExecutor(PropertyHolder.getIntProperty("message.scanner.coreSize", NUM_5), // 设置核心线程数量
        PropertyHolder.getIntProperty("message.scanner.maxPoolSize", NUM_20), // 线程池维护线程的最大数量
        PropertyHolder.getIntProperty("message.scanner.keepAliveSeconds", NUM_600), TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(PropertyHolder.getIntProperty("message.scanner.queueCapacity", NUM_10)) // 允许的空闲时间
    ); // 缓存队列
}
 
Example #26
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * setThreadFactory sets the thread factory returned by getThreadFactory
 */
public void testSetThreadFactory() {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 2,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        ThreadFactory threadFactory = new SimpleThreadFactory();
        p.setThreadFactory(threadFactory);
        assertSame(threadFactory, p.getThreadFactory());
    }
}
 
Example #27
Source File: ArrayBlockingQueueTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * put blocks interruptibly waiting for take when full
 */
public void testPutWithTake() throws InterruptedException {
    final int capacity = 2;
    final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
    final CountDownLatch pleaseTake = new CountDownLatch(1);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            for (int i = 0; i < capacity; i++)
                q.put(i);
            pleaseTake.countDown();
            q.put(86);

            pleaseInterrupt.countDown();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {}
            assertFalse(Thread.interrupted());
        }});

    await(pleaseTake);
    assertEquals(0, q.remainingCapacity());
    assertEquals(0, q.take());

    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
    assertEquals(0, q.remainingCapacity());
}
 
Example #28
Source File: ClientServerWrappedContinuationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTest(final HelloContinuation helloPort) throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 0, TimeUnit.SECONDS,
                                                         new ArrayBlockingQueue<Runnable>(6));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch controlDoneSignal = new CountDownLatch(5);
    CountDownLatch helloDoneSignal = new CountDownLatch(5);

    executor.execute(new ControlWorker(helloPort, "Fred", startSignal, controlDoneSignal));
    executor.execute(new HelloWorker(helloPort, "Fred", "", startSignal, helloDoneSignal));

    executor.execute(new ControlWorker(helloPort, "Barry", startSignal, controlDoneSignal));
    executor.execute(new HelloWorker(helloPort, "Barry", "Jameson", startSignal, helloDoneSignal));

    executor.execute(new ControlWorker(helloPort, "Harry", startSignal, controlDoneSignal));
    executor.execute(new HelloWorker(helloPort, "Harry", "", startSignal, helloDoneSignal));

    executor.execute(new ControlWorker(helloPort, "Rob", startSignal, controlDoneSignal));
    executor.execute(new HelloWorker(helloPort, "Rob", "Davidson", startSignal, helloDoneSignal));

    executor.execute(new ControlWorker(helloPort, "James", startSignal, controlDoneSignal));
    executor.execute(new HelloWorker(helloPort, "James", "ServiceMix", startSignal, helloDoneSignal));

    startSignal.countDown();

    controlDoneSignal.await(100, TimeUnit.SECONDS);
    helloDoneSignal.await(100, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have been resumed", 0, controlDoneSignal.getCount());
    assertEquals("Not all invocations have completed", 0, helloDoneSignal.getCount());

    helloPort.sayHi("Dan1", "to:100");
    helloPort.sayHi("Dan2", "to:100");
    helloPort.sayHi("Dan3", "to:100");
}
 
Example #29
Source File: PlacementDriverServer.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
private ThreadPoolExecutor createDefaultPdExecutor() {
    final int corePoolSize = Math.max(Utils.cpus() << 2, 32);
    final String name = "rheakv-pd-executor";
    return ThreadPoolUtil.newBuilder() //
        .poolName(name) //
        .enableMetric(true) //
        .coreThreads(corePoolSize) //
        .maximumThreads(corePoolSize << 2) //
        .keepAliveSeconds(120L) //
        .workQueue(new ArrayBlockingQueue<>(4096)) //
        .threadFactory(new NamedThreadFactory(name, true)) //
        .rejectedHandler(new CallerRunsPolicyWithReport(name, name)) //
        .build();
}
 
Example #30
Source File: ArrayBlockingQueueTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor throws IAE if capacity argument nonpositive
 */
public void testConstructor2() {
    try {
        new ArrayBlockingQueue(0);
        shouldThrow();
    } catch (IllegalArgumentException success) {}
}