java.util.concurrent.PriorityBlockingQueue Java Examples
The following examples show how to use
java.util.concurrent.PriorityBlockingQueue.
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: PriorityBlockingQueueTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * drainTo empties queue */ public void testDrainToWithActivePut() throws InterruptedException { final PriorityBlockingQueue q = populatedQueue(SIZE); Thread t = new Thread(new CheckedRunnable() { public void realRun() { 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 #2
Source File: PriorityBlockingQueueTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * timed poll transfers elements across Executor tasks */ public void testPollInExecutor() { final PriorityBlockingQueue q = new PriorityBlockingQueue(2); 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)); checkEmpty(q); }}); executor.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { threadsStarted.await(); q.put(one); }}); } }
Example #3
Source File: AStarPathSearch.java From AIBot with GNU General Public License v3.0 | 6 votes |
public AStarPathSearch(AStarPathSearchProvider provider, BlockLocation start, BlockLocation end) { this.provider = provider; this.start = start; this.end = end; heuristic = provider.getHeuristic(); physics = provider.getWorldPhysics(); nodeWorld = new HashMap<BlockLocation, PathNode>(); first = new BlockPathNode(this, start); first.setCost(0); first.setCostEstimate(heuristic.calculateCost(start, end)); openSet = new PriorityBlockingQueue<>(64, PATH_NODE_COMPARATOR); closedSet = new PriorityBlockingQueue<>(64, PATH_NODE_COMPARATOR); nodeWorld.put(start, first); openSet.offer(first); nodeWorldReverse = new HashMap<BlockLocation, PathNode>(); last = new BlockPathNode(this, end); last.setCost(0); last.setCostEstimate(heuristic.calculateCost(end, start)); openSetReverse = new PriorityBlockingQueue<>(64, PATH_NODE_COMPARATOR); closedSetReverse = new PriorityBlockingQueue<>(64, PATH_NODE_COMPARATOR); nodeWorldReverse.put(end, last); openSetReverse.offer(last); }
Example #4
Source File: LongestExpireCacheStrategyTest.java From light-4j with Apache License 2.0 | 6 votes |
@Test public void testCacheJwt() throws NoSuchFieldException, IllegalAccessException { Assert.assertNotNull(cacheStrategy.getCachedJwt(new Jwt.Key(initJwts.get(0).getScopes()))); Field field = LongestExpireCacheStrategy.class.getDeclaredField("expiryQueue"); field.setAccessible(true); PriorityBlockingQueue cachedQueue = (PriorityBlockingQueue) field.get(cacheStrategy); Field field1 = LongestExpireCacheStrategy.class.getDeclaredField("cachedJwts"); field1.setAccessible(true); ConcurrentHashMap<Jwt.Key, Jwt> cachedJwts = (ConcurrentHashMap) field1.get(cacheStrategy); Assert.assertEquals(cachedJwts.size(), 4); Assert.assertEquals(cachedQueue.size(), 4); ArrayList<Jwt> jwts = createJwts(2, initExpiryTime + 10); Jwt jwt5 = jwts.get(0); Jwt jwt1 = cachedJwts.get(cachedQueue.peek()); long originalExpiry = jwt1.getExpire(); Assert.assertEquals(cachedJwts.get(new Jwt.Key(jwt1.getScopes())), jwt1); cacheStrategy.cacheJwt(new Jwt.Key(jwt5.getScopes()), jwt5); Assert.assertEquals(cachedJwts.get(new Jwt.Key(jwt5.getScopes())), jwt5); Assert.assertNotEquals(cachedJwts.get(new Jwt.Key(jwt5.getScopes())).getExpire(), originalExpiry); }
Example #5
Source File: DefaultQueueManager.java From smslib-v3 with Apache License 2.0 | 6 votes |
@Override public boolean removePendingMessage(String messageUUID) { for (PriorityBlockingQueue<OutboundMessage> q : queueMap.values()) { for (OutboundMessage m : q) { if (m.getId().equalsIgnoreCase(messageUUID)) { if (q.remove(m)) { deletePendingMessage(m.getGatewayId(), messageUUID); return true; } } } } return false; }
Example #6
Source File: ExecutorBuilder.java From tomee with Apache License 2.0 | 6 votes |
public BlockingQueue<Runnable> create(final Options options, final String prefix, final int queueSize) { switch (this) { case ARRAY: { return new ArrayBlockingQueue<>(queueSize > 0 ? queueSize : 1); } case LINKED: { return new LinkedBlockingQueue<>(queueSize > 0 ? queueSize : 1); } case PRIORITY: { return new PriorityBlockingQueue<>(); } case SYNCHRONOUS: { return new SynchronousQueue<>(options.get(prefix + ".QueueFair", false)); } default: { // The Options class will throw an error if the user supplies an unknown enum string // The only way we can reach this is if we add a new QueueType element and forget to // implement it in the above switch statement. throw new IllegalArgumentException("Unknown QueueType type: " + this); } } }
Example #7
Source File: StealJobQueue.java From hbase with Apache License 2.0 | 6 votes |
public StealJobQueue(int initCapacity, int stealFromQueueInitCapacity, Comparator<? super T> comparator) { super(initCapacity, comparator); this.stealFromQueue = new PriorityBlockingQueue<T>(stealFromQueueInitCapacity, comparator) { private static final long serialVersionUID = -6805567216580184701L; @Override public boolean offer(T t) { lock.lock(); try { notEmpty.signal(); return super.offer(t); } finally { lock.unlock(); } } }; }
Example #8
Source File: OrderedExecutorLimiter.java From threadly with Mozilla Public License 2.0 | 6 votes |
/** * Construct a new limiter, providing the implementation of how tasks should be sorted relative * to each other. The {@link Comparator} provided must deterministically provide ordering such * that two tasks must always have the same relative order. * <p> * This constructor allows you to specify if listeners / * {@link org.threadly.concurrent.future.FutureCallback}'s / functions in * {@link ListenableFuture#map(java.util.function.Function)} or * {@link ListenableFuture#flatMap(java.util.function.Function)} should be counted towards the * concurrency limit. Specifying {@code false} will release the limit as soon as the original * task completes. Specifying {@code true} will continue to enforce the limit until all listeners * (without an executor) complete. * * @param executor {@link Executor} to submit task executions to. * @param maxConcurrency maximum quantity of tasks to run in parallel * @param limitFutureListenersExecution {@code true} to include listener / mapped functions towards execution limit * @param sorter Implementation of {@link Comparator} to sort the task queue being limited */ @SuppressWarnings("unchecked") public OrderedExecutorLimiter(Executor executor, int maxConcurrency, boolean limitFutureListenersExecution, final Comparator<? super T> sorter) { ArgumentVerifier.assertNotNull(sorter, "sorter"); limiter = new ExecutorLimiter(executor, maxConcurrency, limitFutureListenersExecution, new PriorityBlockingQueue<>(INITIAL_QUEUE_SIZE, (rc1, rc2) -> { T r1 = runnableTypeFromContainer(rc1); T r2 = runnableTypeFromContainer(rc2); return sorter.compare(r1, r2); })) { @Override protected boolean taskCapacity() { checkTaskCapacity(); return super.taskCapacity(); } }; }
Example #9
Source File: Log.java From HolandaCatalinaFw with Apache License 2.0 | 6 votes |
/** * Start the log thread. */ @Override protected void init() { this.printers = new ArrayList<>(); this.queue = new PriorityBlockingQueue<>( SystemProperties.getInteger(SystemProperties.Log.QUEUE_INITIAL_SIZE), (o1, o2) -> (int)(o1.getDate().getTime() - o2.getDate().getTime())); this.logMonitor = new Object(); this.shuttingDown = false; for (int i = 0; i < SystemProperties.getInteger(SystemProperties.Log.LOG_CONSUMERS_SIZE); i++) { fork(new LogRunnable()); } List<String> logConsumers = SystemProperties.getList(SystemProperties.Log.CONSUMERS); logConsumers.forEach(S -> { try { LogPrinter printer = (LogPrinter) Class.forName(S).getConstructor().newInstance(); registerConsumer(printer); } catch (Exception ex){ ex.printStackTrace(); } }); }
Example #10
Source File: DefaultGroovyMethodsSupport.java From groovy with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected static <T> Queue<T> createSimilarQueue(Queue<T> orig) { if (orig instanceof ArrayBlockingQueue) { ArrayBlockingQueue queue = (ArrayBlockingQueue) orig; return new ArrayBlockingQueue<T>(queue.size() + queue.remainingCapacity()); } else if (orig instanceof ArrayDeque) { return new ArrayDeque<T>(); } else if (orig instanceof ConcurrentLinkedQueue) { return new ConcurrentLinkedQueue<T>(); } else if (orig instanceof DelayQueue) { return new DelayQueue(); } else if (orig instanceof LinkedBlockingDeque) { return new LinkedBlockingDeque<T>(); } else if (orig instanceof LinkedBlockingQueue) { return new LinkedBlockingQueue<T>(); } else if (orig instanceof PriorityBlockingQueue) { return new PriorityBlockingQueue<T>(); } else if (orig instanceof PriorityQueue) { return new PriorityQueue<T>(11, ((PriorityQueue) orig).comparator()); } else if (orig instanceof SynchronousQueue) { return new SynchronousQueue<T>(); } else { return new LinkedList<T>(); } }
Example #11
Source File: Partition.java From waltz with Apache License 2.0 | 6 votes |
/** * Class Constructor. * @param partitionId ID of the partition. * @param storePartition {@link StorePartition} associated with the given partition ID. * @param feedCachePartition {@link FeedCachePartition} associated with the given partition ID. * @param transactionFetcher {@link TransactionFetcher} associated with the {@code WaltzServer} to which the partition is part of. * @param config the config of the {@code WaltzServer} to which the partition is part of. */ public Partition(int partitionId, StorePartition storePartition, FeedCachePartition feedCachePartition, TransactionFetcher transactionFetcher, WaltzServerConfig config) { this.partitionId = partitionId; this.lockTableSize = (int) config.get(WaltzServerConfig.OPTIMISTIC_LOCK_TABLE_SIZE); this.minFetchSize = (int) config.get(WaltzServerConfig.MIN_FETCH_SIZE); this.realtimeThreshold = (int) config.get(WaltzServerConfig.REALTIME_THRESHOLD); this.storePartition = storePartition; this.appendTask = new AppendTask(); this.nearRealtimeFeedTask = new FeedTask("R", new PriorityBlockingQueue<>(100, FeedContext.HIGH_WATER_MARK_COMPARATOR)); this.catchupFeedTask = new FeedTask("C", new LinkedBlockingQueue<>()); this.pausedFeedContexts = new LinkedList<>(); this.metricsGroup = String.format("%s.partition-%d", MetricGroup.WALTZ_SERVER_METRIC_GROUP, partitionId); // Register metrics registerMetrics(); this.feedCachePartition = feedCachePartition; this.transactionFetcher = transactionFetcher; }
Example #12
Source File: PriorityBlockingQueueIntegrationTest.java From tutorials with MIT License | 6 votes |
@Test public void whenPollingEmptyQueue_thenShouldBlockThread() throws InterruptedException { PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(); final Thread thread = new Thread(() -> { LOG.debug("Polling..."); while (true) { try { Integer poll = queue.take(); LOG.debug("Polled: " + poll); } catch (InterruptedException ignored) { } } }); thread.start(); Thread.sleep(TimeUnit.SECONDS.toMillis(5)); LOG.debug("Adding to queue"); queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); }
Example #13
Source File: PriorityBlockingQueueTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * drainTo(c) empties queue into another collection c */ public void testDrainTo() { PriorityBlockingQueue q = populatedQueue(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 #14
Source File: MockStore.java From sofa-dashboard with Apache License 2.0 | 6 votes |
@Override public void addRecords(HostAndPort hostAndPort, List<StoreRecord> records) { store.compute(hostAndPort, (key, value) -> { Map<String, Queue<StoreRecord>> data = Optional.ofNullable(value) .orElse(new ConcurrentHashMap<>()); for (StoreRecord record : records) { data.compute(record.getSchemeName(), (dKey, dValue) -> { Queue<StoreRecord> queue = Optional.ofNullable(dValue) .orElse(new PriorityBlockingQueue<>(16, Comparator.comparingLong(o -> o.getTimestamp()))); queue.add(record); return queue; }); } return data; }); }
Example #15
Source File: NonTransactionalAdapterQueue.java From copper-engine with Apache License 2.0 | 6 votes |
public NonTransactionalAdapterQueue(Collection<String> adapterIds, AdapterCallPersisterFactory persistence, int transientQueueLength, int triggerReloadQueueLength, TransactionController ctrl, Batcher batcher) { this.transientQueueLength = transientQueueLength; this.triggerReloadQueueLength = triggerReloadQueueLength; this.persistence = persistence; this.adapterIds = new ArrayList<String>(adapterIds); this.ctrl = ctrl; this.batcher = batcher; this.queue = new PriorityBlockingQueue<AdapterCall>(transientQueueLength, new Comparator<AdapterCall>() { @Override public int compare(AdapterCall o1, AdapterCall o2) { if (o1.getPriority() < o2.getPriority()) return -1; if (o1.getPriority() > o2.getPriority()) return 1; return 0; } }); this.reloadThread = new ReloadThread(); }
Example #16
Source File: PriorityBlockingQueueTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Offer of non-Comparable throws CCE */ public void testOfferNonComparable() { PriorityBlockingQueue q = new PriorityBlockingQueue(1); try { q.offer(new Object()); shouldThrow(); } catch (ClassCastException success) { assertTrue(q.isEmpty()); assertEquals(0, q.size()); assertNull(q.poll()); } }
Example #17
Source File: PriorityBlockingQueueTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * remove removes next element, or throws NSEE if empty */ public void testRemove() { PriorityBlockingQueue q = populatedQueue(SIZE); for (int i = 0; i < SIZE; ++i) { assertEquals(i, q.remove()); } try { q.remove(); shouldThrow(); } catch (NoSuchElementException success) {} }
Example #18
Source File: BoundedElasticScheduler.java From reactor-core with Apache License 2.0 | 5 votes |
BoundedServices(BoundedElasticScheduler parent) { this.parent = parent; this.clock = parent.clock; this.busyQueue = new PriorityBlockingQueue<>(parent.maxThreads, Comparator.comparingInt(bs -> bs.markCount)); this.idleQueue = new ConcurrentLinkedDeque<>(); }
Example #19
Source File: PriorityBlockingQueueTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Initializing from null Collection throws NPE */ public void testConstructor3() { try { new PriorityBlockingQueue(null); shouldThrow(); } catch (NullPointerException success) {} }
Example #20
Source File: PriorityBlockingQueueTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * Queue 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; PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints)); for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll()); }
Example #21
Source File: PriorityBlockingQueueTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * toArray(a) contains all elements */ public void testToArray2() throws InterruptedException { PriorityBlockingQueue<Integer> q = populatedQueue(SIZE); Integer[] ints = new Integer[SIZE]; Integer[] array = q.toArray(ints); assertSame(ints, array); Arrays.sort(ints); for (int i = 0; i < ints.length; i++) assertSame(ints[i], q.take()); }
Example #22
Source File: PriorityBlockingQueueTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * Offer of non-Comparable throws CCE */ public void testOfferNonComparable() { PriorityBlockingQueue q = new PriorityBlockingQueue(1); try { q.offer(new Object()); q.offer(new Object()); shouldThrow(); } catch (ClassCastException success) {} }
Example #23
Source File: PriorityBlockingQueueTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * removeAll(c) removes only those elements of c and reports true if changed */ public void testRemoveAll() { for (int i = 1; i < SIZE; ++i) { PriorityBlockingQueue q = populatedQueue(SIZE); PriorityBlockingQueue p = populatedQueue(i); assertTrue(q.removeAll(p)); assertEquals(SIZE - i, q.size()); for (int j = 0; j < i; ++j) { Integer x = (Integer)(p.remove()); assertFalse(q.contains(x)); } } }
Example #24
Source File: PriorityBlockingQueueTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * toArray(incompatible array type) throws ArrayStoreException */ public void testToArray1_BadArg() { PriorityBlockingQueue q = populatedQueue(SIZE); try { q.toArray(new String[10]); shouldThrow(); } catch (ArrayStoreException success) {} }
Example #25
Source File: VolleyRequestQueue.java From letv with Apache License 2.0 | 5 votes |
public VolleyRequestQueue(Network network, Network fileNetwork, int threadPoolSize, int cacheThreadPoolSize, ResponseDelivery delivery) { this.mSequenceGenerator = new AtomicInteger(); this.mCurrentRequests = new HashSet(); this.mCacheQueue = new PriorityBlockingQueue(); this.mNetworkQueue = new PriorityBlockingQueue(); this.mFileNetworkQueue = new PriorityBlockingQueue(); this.mDispatchers = new NetworkDispatcher[threadPoolSize]; this.mCacheDispatchers = new CacheDispatcher[cacheThreadPoolSize]; this.mDelivery = delivery; }
Example #26
Source File: DefaultQueueManager.java From smslib-v3 with Apache License 2.0 | 5 votes |
private boolean addToGatewayQueue(OutboundMessage message, boolean store) { PriorityBlockingQueue<OutboundMessage> queue = queueMap.get(message.getGatewayId()); if (queue == null) { queue = new PriorityBlockingQueue<OutboundMessage>(50, new PriorityComparator()); queueMap.put(message.getGatewayId(), queue); } boolean queued = queue.add(message); if (store && queued) storePendingMessage(message); return queued; }
Example #27
Source File: AverageSimulateActivity.java From Ticket-Analysis with MIT License | 5 votes |
private void calculateData(List<Integer> numberList, String allNum, String chooseSize, String generateSize, boolean selected) { final int cores = Math.max(1, Runtime.getRuntime().availableProcessors()); final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(cores, cores, 0, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), new DefaultThreadFactory()); Handler handler = getHandler(cores); int generateTaskSize = Integer.valueOf(generateSize); List<Integer> tasks = taskDivider(generateTaskSize, cores); //run all thread showLoadingDialog("正在拼命计算中", false); for (int i = 0; i < cores; i++) { runTask(threadPoolExecutor, handler, allNum, chooseSize, tasks.get(i), numberList,selected); } }
Example #28
Source File: CodeForecastActivity.java From Ticket-Analysis with MIT License | 5 votes |
@Override protected void init() { int cores = Math.max(1, Runtime.getRuntime().availableProcessors()); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(cores, cores, 0, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), new DefaultThreadFactory()); Handler handler = getHandler(cores); rvForecast = (RecyclerView) findViewById(R.id.rvForecast); showLoadingDialog("正在拼命计算中..."); for (int i = 0; i < cores; i++) { threadPoolExecutor.execute(new NumberAvgRunnable(handler, mTicketRegular.regular, mTicketRegular.codeDis, mTicketRegular.repeat)); taskCount++; } }
Example #29
Source File: PeerExchangePeerSourceFactory.java From bt with Apache License 2.0 | 5 votes |
private Queue<PeerEvent> getPeerEvents(TorrentId torrentId) { Queue<PeerEvent> events = peerEvents.get(torrentId); if (events == null) { events = new PriorityBlockingQueue<>(); Queue<PeerEvent> existing = peerEvents.putIfAbsent(torrentId, events); if (existing != null) { events = existing; } } return events; }
Example #30
Source File: Queues.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Creates a {@code PriorityBlockingQueue} containing the given elements. * * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityBlockingQueue<E>(Collections2.cast(elements)); } PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>(); Iterables.addAll(queue, elements); return queue; }