java.util.concurrent.LinkedBlockingDeque Java Examples
The following examples show how to use
java.util.concurrent.LinkedBlockingDeque.
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: ChatController.java From SpringMVC-Project with MIT License | 6 votes |
@Override public void run() { LinkedBlockingDeque<MessageVo> messageQueue = MESSAGE_QUEUE_MAP.get(userId); BaseResponse<List<MessageVo>> response = new BaseResponse<>(); List<MessageVo> list = Lists.newArrayList(); MessageVo vo; try { if ((vo = messageQueue.poll(timeout, TimeUnit.MILLISECONDS)) != null) { list.add(vo); //一次最多取10条信息 for (int i = 0; i < 9; i++) { vo = messageQueue.poll(); if (vo == null) { break; } list.add(vo); } } } catch (InterruptedException e) { e.printStackTrace(); } response.setData(list); deferredResult.setResult(response); }
Example #2
Source File: RemovePollRace.java From hottub with GNU General Public License v2.0 | 6 votes |
Collection<Queue<Boolean>> concurrentQueues() { List<Queue<Boolean>> queues = new ArrayList<Queue<Boolean>>(); queues.add(new ConcurrentLinkedDeque<Boolean>()); queues.add(new ConcurrentLinkedQueue<Boolean>()); queues.add(new ArrayBlockingQueue<Boolean>(count, false)); queues.add(new ArrayBlockingQueue<Boolean>(count, true)); queues.add(new LinkedBlockingQueue<Boolean>()); queues.add(new LinkedBlockingDeque<Boolean>()); queues.add(new LinkedTransferQueue<Boolean>()); // Following additional implementations are available from: // http://gee.cs.oswego.edu/dl/concurrency-interest/index.html // queues.add(new SynchronizedLinkedListQueue<Boolean>()); // Avoid "first fast, second slow" benchmark effect. Collections.shuffle(queues); return queues; }
Example #3
Source File: BlockingQueueTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Main method. * * @param args Parameters. * @throws Exception If failed. */ public static void main(String[] args) throws Exception { for (int i = 0; i < RETRIES; i++) { X.println(">>>"); X.println(">>> Executing single threaded attempt: " + i); X.println(">>>"); testBlockingQueue("single-threaded-linked-queue", new LinkedBlockingQueue<>()); testBlockingQueue("single-threaded-linked-deque", new LinkedBlockingDeque<>()); testBlockingQueue("single-threaded-array-queue", new ArrayBlockingQueue<>(CNT + 10)); } for (int i = 0; i < RETRIES; i++) { X.println(">>>"); X.println(">>> Executing multi-threaded attempt: " + i); X.println(">>>"); testBlockingQueueMultithreaded("multi-threaded-linked-queue", new LinkedBlockingQueue<>()); testBlockingQueueMultithreaded("multi-threaded-linked-deque", new LinkedBlockingDeque<>()); testBlockingQueueMultithreaded("multi-threaded-array-queue", new ArrayBlockingQueue<>( THREAD_CNT * CNT + 100)); } }
Example #4
Source File: TwitterStreamProvider.java From streams with Apache License 2.0 | 6 votes |
@Override public synchronized StreamsResultSet readCurrent() { StreamsResultSet current; synchronized (this) { Queue<StreamsDatum> drain = new LinkedBlockingDeque<>(); drainTo(drain); current = new StreamsResultSet(drain); current.setCounter(new DatumStatusCounter()); current.getCounter().add(countersCurrent); countersTotal.add(countersCurrent); countersCurrent = new DatumStatusCounter(); } return current; }
Example #5
Source File: LinkedBlockingDequeTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * Descending iterator ordering is reverse FIFO */ public void testDescendingIteratorOrdering() { final LinkedBlockingDeque q = new LinkedBlockingDeque(); for (int iters = 0; iters < 100; ++iters) { q.add(new Integer(3)); q.add(new Integer(2)); q.add(new Integer(1)); int k = 0; for (Iterator it = q.descendingIterator(); it.hasNext();) { assertEquals(++k, it.next()); } assertEquals(3, k); q.remove(); q.remove(); q.remove(); } }
Example #6
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * timed offerLast times out if full and elements not taken */ public void testTimedOfferLast() throws InterruptedException { final LinkedBlockingDeque q = new LinkedBlockingDeque(2); final CountDownLatch pleaseInterrupt = new CountDownLatch(1); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() throws InterruptedException { q.putLast(new Object()); q.putLast(new Object()); long startTime = System.nanoTime(); assertFalse(q.offerLast(new Object(), timeoutMillis(), MILLISECONDS)); assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); pleaseInterrupt.countDown(); try { q.offerLast(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (InterruptedException success) {} }}); await(pleaseInterrupt); assertThreadStaysAlive(t); t.interrupt(); awaitTermination(t); }
Example #7
Source File: ChannelStateWriteRequestExecutorImplTest.java From flink with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("CallToThreadRun") public void testCleanup() throws IOException { TestWriteRequest request = new TestWriteRequest(); LinkedBlockingDeque<ChannelStateWriteRequest> deque = new LinkedBlockingDeque<>(); deque.add(request); TestRequestDispatcher requestProcessor = new TestRequestDispatcher(); ChannelStateWriteRequestExecutorImpl worker = new ChannelStateWriteRequestExecutorImpl(TASK_NAME, requestProcessor, deque); worker.close(); worker.run(); assertTrue(requestProcessor.isStopped()); assertTrue(deque.isEmpty()); assertTrue(request.isCancelled()); }
Example #8
Source File: ThreadPoolUtils.java From sofa-ark with Apache License 2.0 | 6 votes |
/** * Build Queue * * @param size size of queue * @param isPriority whether use priority queue or not * @return queue */ public static BlockingQueue<Runnable> buildQueue(int size, boolean isPriority) { BlockingQueue<Runnable> queue; if (size == 0) { queue = new SynchronousQueue<>(); } else { if (isPriority) { queue = size < 0 ? new PriorityBlockingQueue<Runnable>() : new PriorityBlockingQueue<Runnable>(size); } else { queue = size < 0 ? new LinkedBlockingDeque<Runnable>() : new LinkedBlockingDeque<Runnable>(size); } } return queue; }
Example #9
Source File: LinkedBlockingDequeTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * offer transfers elements across Executor tasks */ public void testOfferInExecutor() { final LinkedBlockingDeque q = new LinkedBlockingDeque(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(); assertSame(one, q.take()); }}); } }
Example #10
Source File: RemovePollRace.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
Collection<Queue<Boolean>> concurrentQueues() { List<Queue<Boolean>> queues = new ArrayList<Queue<Boolean>>(); queues.add(new ConcurrentLinkedDeque<Boolean>()); queues.add(new ConcurrentLinkedQueue<Boolean>()); queues.add(new ArrayBlockingQueue<Boolean>(count, false)); queues.add(new ArrayBlockingQueue<Boolean>(count, true)); queues.add(new LinkedBlockingQueue<Boolean>()); queues.add(new LinkedBlockingDeque<Boolean>()); queues.add(new LinkedTransferQueue<Boolean>()); // Following additional implementations are available from: // http://gee.cs.oswego.edu/dl/concurrency-interest/index.html // queues.add(new SynchronizedLinkedListQueue<Boolean>()); // Avoid "first fast, second slow" benchmark effect. Collections.shuffle(queues); return queues; }
Example #11
Source File: DrbdEventService.java From linstor-server with GNU General Public License v3.0 | 6 votes |
@Inject public DrbdEventService( final ErrorReporter errorReporterRef, final DrbdStateTracker trackerRef, final CoreModule.ResourceDefinitionMap rscDfnMap ) { try { instanceName = new ServiceName(INSTANCE_PREFIX + INSTANCE_COUNT.incrementAndGet()); eventDeque = new LinkedBlockingDeque<>(EVENT_QUEUE_DEFAULT_SIZE); demonHandler = new DaemonHandler(eventDeque, DRBDSETUP_COMMAND, "events2", "all"); running = false; errorReporter = errorReporterRef; tracker = trackerRef; eventsMonitor = new DrbdEventsMonitor(trackerRef, errorReporterRef, rscDfnMap); } catch (InvalidNameException invalidNameExc) { throw new ImplementationError(invalidNameExc); } }
Example #12
Source File: JConsoleCLIPlugin.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
private ExecutorService createExecutor() { final ThreadGroup group = new ThreadGroup("management-client-thread"); final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<JBossThreadFactory>() { public JBossThreadFactory run() { return new JBossThreadFactory(group, Boolean.FALSE, null, "%G " + executorCount.incrementAndGet() + "-%t", null, null); } }); return EnhancedQueueExecutor.DISABLE_HINT ? new ThreadPoolExecutor(2, DEFAULT_MAX_THREADS, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), threadFactory) : new EnhancedQueueExecutor.Builder() .setCorePoolSize(2) .setMaximumPoolSize(DEFAULT_MAX_THREADS) .setKeepAliveTime(60, TimeUnit.SECONDS) .setThreadFactory(threadFactory) .build(); }
Example #13
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * iterator iterates through all elements */ public void testIterator() throws InterruptedException { LinkedBlockingDeque q = populatedDeque(SIZE); Iterator it = q.iterator(); int i; for (i = 0; it.hasNext(); i++) assertTrue(q.contains(it.next())); assertEquals(i, SIZE); assertIteratorExhausted(it); it = q.iterator(); for (i = 0; it.hasNext(); i++) assertEquals(it.next(), q.take()); assertEquals(i, SIZE); assertIteratorExhausted(it); }
Example #14
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * drainTo(c) empties deque into another collection c */ public void testDrainTo() { LinkedBlockingDeque q = populatedDeque(SIZE); ArrayList l = new ArrayList(); q.drainTo(l); assertEquals(0, q.size()); assertEquals(SIZE, l.size()); for (int i = 0; i < SIZE; ++i) assertEquals(l.get(i), new Integer(i)); q.add(zero); q.add(one); assertFalse(q.isEmpty()); assertTrue(q.contains(zero)); assertTrue(q.contains(one)); l.clear(); q.drainTo(l); assertEquals(0, q.size()); assertEquals(2, l.size()); for (int i = 0; i < 2; ++i) assertEquals(l.get(i), new Integer(i)); }
Example #15
Source File: RocketMQTransactionConfiguration.java From rocketmq-spring with Apache License 2.0 | 6 votes |
private void registerTransactionListener(String beanName, Object bean) { Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean); if (!RocketMQLocalTransactionListener.class.isAssignableFrom(bean.getClass())) { throw new IllegalStateException(clazz + " is not instance of " + RocketMQLocalTransactionListener.class.getName()); } RocketMQTransactionListener annotation = clazz.getAnnotation(RocketMQTransactionListener.class); RocketMQTemplate rocketMQTemplate = (RocketMQTemplate) applicationContext.getBean(annotation.rocketMQTemplateBeanName()); if (((TransactionMQProducer) rocketMQTemplate.getProducer()).getTransactionListener() != null) { throw new IllegalStateException(annotation.rocketMQTemplateBeanName() + " already exists RocketMQLocalTransactionListener"); } ((TransactionMQProducer) rocketMQTemplate.getProducer()).setExecutorService(new ThreadPoolExecutor(annotation.corePoolSize(), annotation.maximumPoolSize(), annotation.keepAliveTime(), TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(annotation.blockingQueueSize()))); ((TransactionMQProducer) rocketMQTemplate.getProducer()).setTransactionListener(RocketMQUtil.convert((RocketMQLocalTransactionListener) bean)); log.debug("RocketMQLocalTransactionListener {} register to {} success", clazz.getName(), annotation.rocketMQTemplateBeanName()); }
Example #16
Source File: JobExecutor.java From octoandroid with GNU General Public License v3.0 | 5 votes |
@Inject public JobExecutor() { this.mWorkQueue = new LinkedBlockingDeque<>(); this.mThreadFactory = new JobThreadFactory(); this.mThreadPoolExecutor = new ThreadPoolExecutor(INITIAL_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mWorkQueue, mThreadFactory); }
Example #17
Source File: Percentile.java From attic-aurora with Apache License 2.0 | 5 votes |
/** * Creates a new percentile tracker. * * A percentile tracker will randomly sample recorded events with the given sampling rate, and * will automatically register variables to track the percentiles requested. * When allowFlushAfterSample is set to true, once the last percentile is sampled, * all recorded values are flushed in preparation for the next window; otherwise, the percentile * is calculated using the moving window of the most recent values. * * @param name The name of the value whose percentile is being tracked. * @param numSampleWindows How many sampling windows are used for calculation. * @param sampler The sampler to use for selecting recorded events. You may set sampler to null * to sample all input. * @param percentiles The percentiles to track. */ public Percentile(String name, int numSampleWindows, @Nullable Sampler sampler, double... percentiles) { MorePreconditions.checkNotBlank(name); Preconditions.checkArgument(numSampleWindows >= 1, "Must have one or more sample windows."); Preconditions.checkNotNull(percentiles); Preconditions.checkArgument(percentiles.length > 0, "Must specify at least one percentile."); this.sampler = sampler; sampleQueue = new LinkedBlockingDeque<ArrayList<T>>(numSampleWindows); ImmutableMap.Builder<Double, SampledStat<Double>> builder = new ImmutableMap.Builder<Double, SampledStat<Double>>(); for (int i = 0; i < percentiles.length; i++) { boolean sortFirst = i == 0; String statName = String.format("%s_%s_percentile", name, percentiles[i]) .replace('.', '_'); SampledStat<Double> stat = new PercentileVar(statName, percentiles[i], sortFirst); Stats.export(stat); builder.put(percentiles[i], stat); } statsByPercentile = builder.build(); }
Example #18
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Deque contains all elements of collection used to initialize */ public void testConstructor6() { Integer[] ints = new Integer[SIZE]; for (int i = 0; i < SIZE; ++i) ints[i] = i; LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints)); for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll()); }
Example #19
Source File: AbstractMySqlBinlogCdcIntegrationIT.java From light-eventuate-4j with Apache License 2.0 | 5 votes |
@Test public void shouldGetEvents() throws IOException, TimeoutException, InterruptedException, ExecutionException { MySqlBinaryLogClient<PublishedEvent> mySqlBinaryLogClient = new MySqlBinaryLogClient<>(eventDataParser, cdcConfig.getDbUser(), cdcConfig.getDbPass(), cdcConfig.getDbHost(), cdcConfig.getDbPort(), cdcConfig.getBinlogClientId(), sourceTableNameSupplier.getSourceTableName(), cdcConfig.getMySqlBinLogClientName()); EventuateLocalAggregateCrud localAggregateCrud = new EventuateLocalAggregateCrud(eventuateJdbcAccess); BlockingQueue<PublishedEvent> publishedEvents = new LinkedBlockingDeque<>(); mySqlBinaryLogClient.start(Optional.empty(), publishedEvents::add); String accountCreatedEventData = generateAccountCreatedEvent(); EntityIdVersionAndEventIds saveResult = saveEvent(localAggregateCrud, accountCreatedEventData); String accountDebitedEventData = generateAccountDebitedEvent(); EntityIdVersionAndEventIds updateResult = updateEvent(saveResult.getEntityId(), saveResult.getEntityVersion(), localAggregateCrud, accountDebitedEventData); // Wait for 10 seconds LocalDateTime deadline = LocalDateTime.now().plusSeconds(20); waitForEvent(publishedEvents, saveResult.getEntityVersion(), deadline, accountCreatedEventData); waitForEvent(publishedEvents, updateResult.getEntityVersion(), deadline, accountDebitedEventData); mySqlBinaryLogClient.stop(); }
Example #20
Source File: MinerStatisticsCalculator.java From aion with MIT License | 5 votes |
MinerStatisticsCalculator(ChainHolder chainHolder, int size, int blockTimeCount) { this.chainHolder = chainHolder; this.size = size; aionBlockCache = new LinkedBlockingDeque<>(size * 2); // will always store elements in the reverse // of natural order, ie. n-1th element>nth element this.blockTimeCount = blockTimeCount; statsHistory = Collections.synchronizedMap(new LRUMap<>(size * 2)); }
Example #21
Source File: LinkedBlockingDequeTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * clear removes all elements */ public void testClear() { LinkedBlockingDeque q = populatedDeque(SIZE); q.clear(); assertTrue(q.isEmpty()); assertEquals(0, q.size()); assertEquals(SIZE, q.remainingCapacity()); q.add(one); assertFalse(q.isEmpty()); assertTrue(q.contains(one)); q.clear(); assertTrue(q.isEmpty()); }
Example #22
Source File: LinkedBlockingDequeTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * Initializing from null Collection throws NullPointerException */ public void testConstructor3() { try { new LinkedBlockingDeque(null); shouldThrow(); } catch (NullPointerException success) {} }
Example #23
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * peekLast returns element inserted with addLast */ public void testAddLast() { LinkedBlockingDeque q = populatedDeque(3); q.pollLast(); q.addLast(four); assertSame(four, q.peekLast()); }
Example #24
Source File: TimeCacheQueue.java From jstorm with Apache License 2.0 | 5 votes |
public void offer(K entry) { synchronized (_lock) { LinkedBlockingDeque<K> bucket = _buckets.getFirst(); bucket.offer(entry); } }
Example #25
Source File: LinkedBlockingDequeTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * Returns a new deque of given size containing consecutive * Integers 0 ... n. */ private LinkedBlockingDeque<Integer> populatedDeque(int n) { LinkedBlockingDeque<Integer> q = new LinkedBlockingDeque<Integer>(n); assertTrue(q.isEmpty()); for (int i = 0; i < n; i++) assertTrue(q.offer(new Integer(i))); assertFalse(q.isEmpty()); assertEquals(0, q.remainingCapacity()); assertEquals(n, q.size()); return q; }
Example #26
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Returns a new deque of given size containing consecutive * Integers 0 ... n - 1. */ private LinkedBlockingDeque<Integer> populatedDeque(int n) { LinkedBlockingDeque<Integer> q = new LinkedBlockingDeque<Integer>(n); assertTrue(q.isEmpty()); for (int i = 0; i < n; i++) assertTrue(q.offer(new Integer(i))); assertFalse(q.isEmpty()); assertEquals(0, q.remainingCapacity()); assertEquals(n, q.size()); assertEquals((Integer) 0, q.peekFirst()); assertEquals((Integer) (n - 1), q.peekLast()); return q; }
Example #27
Source File: JdbcMetrics.java From apiman with Apache License 2.0 | 5 votes |
/** * Constructor. * @param config map of configuration options */ public JdbcMetrics(Map<String, String> config) { super(config); int queueSize = DEFAULT_QUEUE_SIZE; String queueSizeConfig = config.get("queue.size"); //$NON-NLS-1$ if (queueSizeConfig != null) { queueSize = new Integer(queueSizeConfig); } queue = new LinkedBlockingDeque<>(queueSize); startConsumerThread(); }
Example #28
Source File: Rate.java From attic-aurora with Apache License 2.0 | 5 votes |
private Rate(String name, Supplier<T> inputAccessor, int windowSize, double scaleFactor, Ticker ticker) { super(name, 0d); this.inputAccessor = Preconditions.checkNotNull(inputAccessor); this.ticker = Preconditions.checkNotNull(ticker); samples = new LinkedBlockingDeque<Pair<Long, Double>>(windowSize); Preconditions.checkArgument(scaleFactor != 0, "Scale factor must be non-zero!"); this.scaleFactor = scaleFactor; }
Example #29
Source File: LinkedBlockingDequeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Deque transitions from empty to full when elements added */ public void testEmptyFull() { LinkedBlockingDeque q = new LinkedBlockingDeque(2); assertTrue(q.isEmpty()); assertEquals("should have room for 2", 2, q.remainingCapacity()); q.add(one); assertFalse(q.isEmpty()); q.add(two); assertFalse(q.isEmpty()); assertEquals(0, q.remainingCapacity()); assertFalse(q.offer(three)); }
Example #30
Source File: LinkedBlockingDequeTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * push succeeds if not full; throws ISE if full */ public void testPush() { LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE); for (int i = 0; i < SIZE; ++i) { Integer x = new Integer(i); q.push(x); assertEquals(x, q.peek()); } assertEquals(0, q.remainingCapacity()); try { q.push(new Integer(SIZE)); shouldThrow(); } catch (IllegalStateException success) {} }