當前位置: 首頁>>代碼示例>>Java>>正文


Java SynchronousQueue類代碼示例

本文整理匯總了Java中java.util.concurrent.SynchronousQueue的典型用法代碼示例。如果您正苦於以下問題:Java SynchronousQueue類的具體用法?Java SynchronousQueue怎麽用?Java SynchronousQueue使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SynchronousQueue類屬於java.util.concurrent包,在下文中一共展示了SynchronousQueue類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: poolServer

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
@Bean(name = "pool-server")
public TServer poolServer() throws Exception {
	TServerTransport transport = new TServerSocket(this.port());

	TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport);
	args.transportFactory(new TTransportFactory());
	args.protocolFactory(new TBinaryProtocol.Factory());

	args.processor(this.processor());
	args.executorService(new ThreadPoolExecutor(env.getProperty(
			"rpc.server.min.worker.threads", Integer.class, 512), env
			.getProperty("rpc.server.max.worker.threads", Integer.class,
					65535), env.getProperty(
			"rpc.server.thread.keep.alive.time", Long.class, 600l),
			TimeUnit.SECONDS, new SynchronousQueue<Runnable>()));

	return new TThreadPoolServer(args);
}
 
開發者ID:jigsaw-projects,項目名稱:jigsaw-payment,代碼行數:19,代碼來源:HelloServerConfig.java

示例2: newExecutorService

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
private static ExecutorService newExecutorService(
    ThreadFactory threadFactory, String threadName) {
  boolean background = threadFactory instanceof GaeThreadFactory
      && ((GaeThreadFactory) threadFactory).isUsingBackgroundThreads();
  if (background) {
    // Create a thread pool with long-lived threads if background thread support is available.
    return new RevivingScheduledExecutor(threadFactory, threadName, true);
  } else {
    // Create an executor that creates a new thread for each submitted task, when background
    // thread support is not available.
    return new ThreadPoolExecutor(
        0,
        Integer.MAX_VALUE,
        0L,
        TimeUnit.SECONDS,
        new SynchronousQueue<Runnable>(),
        threadFactory);
  }
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:20,代碼來源:GaeExecutorService.java

示例3: createAsynchronousChannelGroup

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
private static AsynchronousChannelGroup createAsynchronousChannelGroup() {
	// Need to do this with the right thread context class loader else the
	// first web app to call this will trigger a leak
	ClassLoader original = Thread.currentThread().getContextClassLoader();

	try {
		Thread.currentThread().setContextClassLoader(AsyncIOThreadFactory.class.getClassLoader());

		// These are the same settings as the default
		// AsynchronousChannelGroup
		int initialSize = Runtime.getRuntime().availableProcessors();
		ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, Long.MAX_VALUE,
				TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new AsyncIOThreadFactory());

		try {
			return AsynchronousChannelGroup.withCachedThreadPool(executorService, initialSize);
		} catch (IOException e) {
			// No good reason for this to happen.
			throw new IllegalStateException(sm.getString("asyncChannelGroup.createFail"));
		}
	} finally {
		Thread.currentThread().setContextClassLoader(original);
	}
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:25,代碼來源:AsyncChannelGroupUtil.java

示例4: start

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
public synchronized void start(CommandExecutor commandExecutor) {
    if (isStarted()) {
        return;
    }

    this.commandExecutor = requireNonNull(commandExecutor, "commandExecutor");

    scheduler = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor(
            new DefaultThreadFactory("mirroring-scheduler", true)));

    worker = MoreExecutors.listeningDecorator(
            new ThreadPoolExecutor(0, numThreads, 1, TimeUnit.MINUTES, new SynchronousQueue<>(),
                                   new DefaultThreadFactory("mirroring-worker", true)));

    final ListenableScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(
            this::schedulePendingMirrors,
            TICK.getSeconds(), TICK.getSeconds(), TimeUnit.SECONDS);

    FuturesExtra.addFailureCallback(
            future,
            cause -> logger.error("Git-to-CD mirroring scheduler stopped due to an unexpected exception:",
                                  cause));
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:24,代碼來源:DefaultMirroringService.java

示例5: testGet_concurrent

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
public void testGet_concurrent() {
  assertTrue(ArbitraryInstances.get(BlockingDeque.class).isEmpty());
  assertTrue(ArbitraryInstances.get(BlockingQueue.class).isEmpty());
  assertTrue(ArbitraryInstances.get(DelayQueue.class).isEmpty());
  assertTrue(ArbitraryInstances.get(SynchronousQueue.class).isEmpty());
  assertTrue(ArbitraryInstances.get(PriorityBlockingQueue.class).isEmpty());
  assertTrue(ArbitraryInstances.get(ConcurrentMap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(ConcurrentNavigableMap.class).isEmpty());
  ArbitraryInstances.get(Executor.class).execute(ArbitraryInstances.get(Runnable.class));
  assertNotNull(ArbitraryInstances.get(ThreadFactory.class));
  assertFreshInstanceReturned(
      BlockingQueue.class, BlockingDeque.class, PriorityBlockingQueue.class,
      DelayQueue.class, SynchronousQueue.class,
      ConcurrentMap.class, ConcurrentNavigableMap.class,
      AtomicReference.class, AtomicBoolean.class,
      AtomicInteger.class, AtomicLong.class, AtomicDouble.class);
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:18,代碼來源:ArbitraryInstancesTest.java

示例6: FixedThreadPoolQueuesExecutor

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
public FixedThreadPoolQueuesExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        ThreadFactory threadFactory,WaitConditionStrategy waitConditionStrategy) {
    super(DEFAULT_INITIAL_THREAD_POOL_SIZE, 1, keepAliveTime, unit, new SynchronousQueue<Runnable>(),
            threadFactory, new AbortPolicy());

    if (corePoolSize < DEFAULT_INITIAL_THREAD_POOL_SIZE) {
        throw new IllegalArgumentException("corePoolSize: " + corePoolSize);
    }

    if ((maximumPoolSize == 0) || (maximumPoolSize < corePoolSize)) {
        throw new IllegalArgumentException("maximumPoolSize: " + maximumPoolSize);
    }
    if(waitConditionStrategy==null)
    {
    	 throw new IllegalArgumentException("waitConditionStrategy: " + waitConditionStrategy);
    }
    // Now, we can setup the pool sizes
    super.setCorePoolSize(corePoolSize);
    super.setMaximumPoolSize(maximumPoolSize);
    this.waitConditionStrategy=waitConditionStrategy;
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:22,代碼來源:FixedThreadPoolQueuesExecutor.java

示例7: FixedThreadPoolBlockingQueuesExecutor

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
/**
 * Creates a new instance of a OrderedThreadPoolExecutor.
 * 
 * @param corePoolSize The initial pool sizePoolSize
 * @param maximumPoolSize The maximum pool size
 * @param keepAliveTime Default duration for a thread
 * @param unit Time unit used for the keepAlive value
 * @param threadFactory The factory used to create threads
 * @param eventQueueHandler The queue used to store events
 */
public FixedThreadPoolBlockingQueuesExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        ThreadFactory threadFactory) {
    // We have to initialize the pool with default values (0 and 1) in order to
    // handle the exception in a better way. We can't add a try {} catch() {}
    // around the super() call.
    super(DEFAULT_INITIAL_THREAD_POOL_SIZE, 1, keepAliveTime, unit, new SynchronousQueue<Runnable>(),
            threadFactory, new AbortPolicy());

    if (corePoolSize < DEFAULT_INITIAL_THREAD_POOL_SIZE) {
        throw new IllegalArgumentException("corePoolSize: " + corePoolSize);
    }

    if ((maximumPoolSize == 0) || (maximumPoolSize < corePoolSize)) {
        throw new IllegalArgumentException("maximumPoolSize: " + maximumPoolSize);
    }

    // Now, we can setup the pool sizes
    super.setCorePoolSize(corePoolSize);
    super.setMaximumPoolSize(maximumPoolSize);
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:31,代碼來源:FixedThreadPoolBlockingQueuesExecutor.java

示例8: testDrainToN

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
/**
 * drainTo(c, n) empties up to n elements of queue into c
 */
public void testDrainToN() throws InterruptedException {
    final SynchronousQueue q = new SynchronousQueue();
    Thread t1 = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            q.put(one);
        }});

    Thread t2 = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            q.put(two);
        }});

    ArrayList l = new ArrayList();
    int drained;
    while ((drained = q.drainTo(l, 1)) == 0) Thread.yield();
    assertEquals(1, drained);
    assertEquals(1, l.size());
    while ((drained = q.drainTo(l, 1)) == 0) Thread.yield();
    assertEquals(1, drained);
    assertEquals(2, l.size());
    assertTrue(l.contains(one));
    assertTrue(l.contains(two));
    awaitTermination(t1);
    awaitTermination(t2);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:29,代碼來源:SynchronousQueueTest.java

示例9: testPollInExecutor

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
public void testPollInExecutor(boolean fair) {
    final SynchronousQueue q = new SynchronousQueue(fair);
    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 {
                assertNull(q.poll());
                threadsStarted.await();
                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
                assertTrue(q.isEmpty());
            }});

        executor.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                threadsStarted.await();
                q.put(one);
            }});
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:SynchronousQueueTest.java

示例10: createExecutor

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
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());
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:17,代碼來源:TcpServer.java

示例11: testSerialization

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
/**
 * a deserialized/reserialized queue is usable
 */
public void testSerialization() {
    final SynchronousQueue x = new SynchronousQueue();
    final SynchronousQueue y = new SynchronousQueue(false);
    final SynchronousQueue z = new SynchronousQueue(true);
    assertSerialEquals(x, y);
    assertNotSerialEquals(x, z);
    SynchronousQueue[] qs = { x, y, z };
    for (SynchronousQueue q : qs) {
        SynchronousQueue clone = serialClone(q);
        assertNotSame(q, clone);
        assertSerialEquals(q, clone);
        assertTrue(clone.isEmpty());
        assertEquals(0, clone.size());
        assertEquals(0, clone.remainingCapacity());
        assertFalse(clone.offer(zero));
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:SynchronousQueueTest.java

示例12: main

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
public static void main(String[] args) throws Exception {
     final int maxConsumers = (args.length > 0)
         ? Integer.parseInt(args[0])
         : 5;

     pool = Executors.newCachedThreadPool();
     for (int i = 1; i <= maxConsumers; i += (i+1) >>> 1) {
         // Adjust iterations to limit typical single runs to <= 10 ms;
         // Notably, fair queues get fewer iters.
         // Unbounded queues can legitimately OOME if iterations
         // high enough, but we have a sufficiently low limit here.
         run(new ArrayBlockingQueue<Integer>(100), i, 1000);
         run(new LinkedBlockingQueue<Integer>(100), i, 1000);
         run(new LinkedBlockingDeque<Integer>(100), i, 1000);
         run(new LinkedTransferQueue<Integer>(), i, 700);
         run(new PriorityBlockingQueue<Integer>(), i, 1000);
         run(new SynchronousQueue<Integer>(), i, 300);
         run(new SynchronousQueue<Integer>(true), i, 200);
         run(new ArrayBlockingQueue<Integer>(100, true), i, 100);
     }
     pool.shutdown();
     if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
         throw new Error();
     pool = null;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:26,代碼來源:SingleProducerMultipleConsumerLoops.java

示例13: setUp

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
    this.count = 3;
    this.peers = new HashMap<Long,QuorumServer>(count);
    peerQuorumPort = new int[count];
    peerClientPort = new int[count];
    authzHosts = new HashSet<String>();
    for(int i = 0; i < count; i++) {
        peerQuorumPort[i] = PortAssignment.unique();
        peerClientPort[i] = PortAssignment.unique();
        QuorumServer qs = new QuorumServer(i, "0.0.0.0",
                peerQuorumPort[i], PortAssignment.unique(), null);
        peers.put(Long.valueOf(i), qs);
        authzHosts.add(qs.hostname);
    }
    executor = new ThreadPoolExecutor(3, 10,
            60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:19,代碼來源:QuorumCnxManagerTest.java

示例14: testDrainToWithActivePut

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
public void testDrainToWithActivePut(boolean fair) {
    final SynchronousQueue q = new SynchronousQueue(fair);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            q.put(one);
        }});

    ArrayList l = new ArrayList();
    long startTime = System.nanoTime();
    while (l.isEmpty()) {
        q.drainTo(l);
        if (millisElapsedSince(startTime) > LONG_DELAY_MS)
            fail("timed out");
        Thread.yield();
    }
    assertEquals(1, l.size());
    assertSame(one, l.get(0));
    awaitTermination(t);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:SynchronousQueueTest.java

示例15: createBlockingQueue

import java.util.concurrent.SynchronousQueue; //導入依賴的package包/類
private BlockingQueue<Runnable> createBlockingQueue() {
    BlockingQueueTypeEnum queueType = BlockingQueueTypeEnum.fromString(txConfig.getBlockingQueueType());

    switch (queueType) {
        case LINKED_BLOCKING_QUEUE:
            return new LinkedBlockingQueue<>(1024);
        case ARRAY_BLOCKING_QUEUE:
            return new ArrayBlockingQueue<>(MAX_ARRAY_QUEUE);
        case SYNCHRONOUS_QUEUE:
            return new SynchronousQueue<>();
        default:
            return new LinkedBlockingQueue<>(1024);
    }

}
 
開發者ID:yu199195,項目名稱:happylifeplat-transaction,代碼行數:16,代碼來源:TransactionThreadPool.java


注:本文中的java.util.concurrent.SynchronousQueue類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。