本文整理汇总了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);
}
示例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);
}
}
示例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);
}
}
示例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));
}
示例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);
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}});
}
}
示例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());
}
示例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));
}
}
示例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;
}
示例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>());
}
示例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);
}
示例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);
}
}