public void jdkQueue() { Queue<Integer> queue = new LinkedList<Integer>(); PrinterUtils.printELog("队列大小:" + queue.size()); Integer arr[] = {1, 2, 3, 4, 5}; //队列里放元素 for (int i : arr) { queue.offer(i); } PrinterUtils.printELog("队列大小:" + queue.size()); //移除 while (!queue.isEmpty()) { PrinterUtils.printELog( "队列头部元素:" + queue.peek() + ",出队:" + queue.poll()); } }
/** * Send update notifications to listeners * @param updates the updates to process. */ protected void processUpdates(Queue<DeviceUpdate> updates) { if (updates == null) return; DeviceUpdate update = null; while (null != (update = updates.poll())) { if (logger.isTraceEnabled()) { logger.trace("Dispatching device update: {}", update); } if (update.change == DeviceUpdate.Change.DELETE) { deviceSyncManager.removeDevice(update.device); } else { deviceSyncManager.storeDevice(update.device); } List<IDeviceListener> listeners = deviceListeners.getOrderedListeners(); notifyListeners(listeners, update); } }
/** * A deserialized/reserialized deque has same elements in same order */ public void testSerialization() throws Exception { Queue x = populatedDeque(SIZE); Queue y = serialClone(x); assertNotSame(y, x); assertEquals(x.size(), y.size()); assertEquals(x.toString(), y.toString()); assertEquals(Arrays.toString(x.toArray()), Arrays.toString(y.toArray())); assertTrue(Arrays.equals(x.toArray(), y.toArray())); while (!x.isEmpty()) { assertFalse(y.isEmpty()); assertEquals(x.remove(), y.remove()); } assertTrue(y.isEmpty()); }
void sendCommand(Handler<AsyncResult<Queue<byte[]>>> handler, String key, Object... params) { if (batches != null) { batches.add(new BatchCommand(key, params, handler)); return; } switch (status) { case Normal: connecter.tryGetConnection(F.ofSucceededVoid(handler, conn -> conn.execute(key, params, handler))); break; case Once: connecter.tryGetConnection(F.ofSucceededVoid(handler, conn -> conn.execute(key, params, F.ofSucceeded(handler, () -> { status = Status.Unusable; vertx.runOnContext(event -> close(F.noneHandle())); }, queue -> queue)))); break; case Unusable: handler.handle(F.failedFuture(new SSDBClosedException())); break; } }
public boolean removeListener(String channelName, EventListener msgListener) { Queue<RedisPubSubListener<?>> listeners = channelListeners.get(channelName); for (RedisPubSubListener<?> listener : listeners) { if (listener instanceof PubSubMessageListener) { if (((PubSubMessageListener)listener).getListener() == msgListener) { removeListener(channelName, listener); return true; } } if (listener instanceof PubSubPatternMessageListener) { if (((PubSubPatternMessageListener)listener).getListener() == msgListener) { removeListener(channelName, listener); return true; } } } return false; }
@ValidationExecutor private void validateMessage(Message m, Group g) { MessageValidator v = validators.get(g.getClientId()); if (v == null) { if (LOG.isLoggable(WARNING)) LOG.warning("No validator for " + g.getClientId().getString()); } else { try { MessageContext context = v.validateMessage(m, g); storeMessageContextAsync(m, g.getClientId(), context); } catch (InvalidMessageException e) { if (LOG.isLoggable(INFO)) LOG.log(INFO, e.toString(), e); Queue<MessageId> invalidate = new LinkedList<MessageId>(); invalidate.add(m.getId()); invalidateNextMessageAsync(invalidate); } } }
private static List<Integer> createConnectedComponent(HashMap<Integer, List<Integer>> graph, int root) { Queue<Integer> q = new ArrayDeque<>(); // next nodes to visit List<Integer> visited = new ArrayList<>(); // connected component so far q.add(root); // init queue while (!q.isEmpty()) { Integer poll = q.poll(); // get next node if (!visited.contains(poll)) { // if it's not already visited visited.add(poll); // visit it q.addAll(graph.get(poll)); // and put its neighbourhood in the queue } } visited.forEach(v -> graph.remove(v)); // removes the connected component from the graph return visited; }
@Override public void parseTokensToValuesAndOperations(int j, String token, Queue<Float> values, Queue<String> operations) { switch (token) { case PLUS_CHAR: case MINUS_CHAR: // adding 0 as a first value when nothing before to start with a pair of values if (j == 0) { values.add(0f); } operations.add(token); break; default: values.add(Float.parseFloat(token)); break; } }
public static int width(TreeNode t) { int maxWdith = 0, levelWidth = 0; Queue<TreeNode> q = new LinkedList<>(); q.add(t); q.add(null); while (!q.isEmpty()) { if (null == (t = q.poll())) { if (levelWidth > maxWdith) maxWdith = levelWidth; levelWidth = 0; if (null != q.peek()) q.add(null); } else { levelWidth++; if (null != t.getLeft()) q.add(t.getLeft()); if (null != t.getRight()) q.add(t.getRight()); } } return maxWdith; }
public Set<Vertex> topologicalSort(Vertex startNode,Set<Vertex> set){ Queue<Vertex> queue=new LinkedList<>(); queue.add(startNode); while(!queue.isEmpty()){ Vertex u=queue.poll(); set.add(u); for(Vertex v : u.adjacents) { if(!set.contains(v)){ v.inDegree--; if(v.inDegree==0) queue.add(v); } else return new HashSet<Vertex>(); } } return set; }
void test(final Queue<Integer> q) throws Throwable { System.out.println(q.getClass().getSimpleName()); pool = Executors.newCachedThreadPool(); print = false; print = false; System.out.println("Warmup..."); oneRun(1, items, q); oneRun(3, items, q); print = true; for (int i = 1; i <= maxStages; i += (i+1) >>> 1) { oneRun(i, items, q); } pool.shutdown(); check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); }
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; }
private void computeSpreadBlockLight(int x, int y, int z, int currentLight, Queue<Vector3> queue, Map<BlockVector3, Boolean> visited) { int current = this.getBlockLightAt(x, y, z); BlockVector3 index = Level.blockHash(x, y, z); if (current < currentLight) { this.setBlockLightAt(x, y, z, currentLight); if (!visited.containsKey(index)) { visited.put(index, true); if (currentLight > 1) { queue.add(new Vector3(x, y, z)); } } } }
void traverse(Node root) { Queue<Node> layer = new LinkedList<>(); layer.offer(root); while (!layer.isEmpty()) { Queue<Node> nextLayer = new LinkedList<>(); Node node = layer.poll(); while (node != null) { System.out.println(node.name); if (node.left != null) { nextLayer.offer(node.left); } if (node.right != null) { nextLayer.offer(node.right); } node = layer.poll(); } layer = nextLayer; } }
protected void computeTargetShare(int nrStudents, Collection<CurriculumCourse> courses, CurriculumCourseGroupsProvider course2groups, CurModel model) { for (CurriculumCourse c1: courses) { float x1 = c1.getPercShare() * nrStudents; Set<CurriculumCourse>[] group = new HashSet[] { new HashSet<CurriculumCourse>(), new HashSet<CurriculumCourse>()}; Queue<CurriculumCourse> queue = new LinkedList<CurriculumCourse>(); queue.add(c1); Set<CurriculumCourseGroup> done = new HashSet<CurriculumCourseGroup>(); while (!queue.isEmpty()) { CurriculumCourse c = queue.poll(); for (CurriculumCourseGroup g: course2groups.getGroups(c)) if (done.add(g)) for (CurriculumCourse x: courses) if (!x.equals(c) && !x.equals(c1) && course2groups.getGroups(x).contains(g) && group[group[0].contains(c) ? 0 : g.getType()].add(x)) queue.add(x); } for (CurriculumCourse c2: courses) { float x2 = c2.getPercShare() * nrStudents; if (c1.getUniqueId() >= c2.getUniqueId()) continue; float share = c1.getPercShare() * c2.getPercShare() * nrStudents; boolean opt = group[0].contains(c2); boolean req = !opt && group[1].contains(c2); model.setTargetShare(c1.getUniqueId(), c2.getUniqueId(), opt ? 0.0 : req ? Math.min(x1, x2) : share, true); } } }
/** * Allocate a direct buffer of the specified size, in bytes. * If a pooled buffer is available, returns that. Otherwise * allocates a new one. */ public ByteBuffer getBuffer(int size) { Queue<WeakReference<ByteBuffer>> list = buffersBySize.get(size); if (list == null) { // no available buffers for this size return ByteBuffer.allocateDirect(size); } WeakReference<ByteBuffer> ref; while ((ref = list.poll()) != null) { ByteBuffer b = ref.get(); if (b != null) { return b; } } return ByteBuffer.allocateDirect(size); }
private static void print(Tree tree) { Queue<Tree.Node> queue = new LinkedList<>(); Tree.Node root = tree.root; queue.add(root); while (!queue.isEmpty()) { Tree.Node poll = queue.poll(); if (poll.left != null) { queue.add(poll.left); } if (poll.right != null) { queue.add(poll.right); } System.out.println(poll.value); } }
public Queue<Object> getObject(final String command) throws Exception { final Object templates = Gadgets.createTemplatesImpl(command); // mock method name until armed final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]); // create queue with numbers and basic comparator final PriorityQueue<Object> queue = new PriorityQueue<Object>(2,new TransformingComparator(transformer)); // stub data for replacement later queue.add(1); queue.add(1); // switch method called by comparator Reflections.setFieldValue(transformer, "iMethodName", "newTransformer"); // switch contents of queue final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue"); queueArray[0] = templates; queueArray[1] = 1; return queue; }
/** * Setup the receives and send sendBuffers */ protected void setupCommunication() { // we will receive from these int maxReceiveBuffers = MPIContext.receiveBufferCount(config); int receiveBufferSize = MPIContext.bufferSize(config); for (Integer recv : receivingExecutors) { Queue<MPIBuffer> recvList = new LinkedList<>(); for (int i = 0; i < maxReceiveBuffers; i++) { recvList.add(new MPIBuffer(receiveBufferSize)); } // register with the channel LOG.info(instancePlan.getThisExecutor() + " Register to receive from: " + recv); channel.receiveMessage(recv, edge, this, recvList); receiveBuffers.put(recv, recvList); } // configure the send sendBuffers int sendBufferSize = MPIContext.bufferSize(config); int sendBufferCount = MPIContext.sendBuffersCount(config); for (int i = 0; i < sendBufferCount; i++) { MPIBuffer buffer = new MPIBuffer(sendBufferSize); sendBuffers.offer(buffer); } }
@SuppressWarnings ( { "rawtypes", "unchecked" } ) public static Queue<Object> makePriorityQueue ( Object tgt, Comparator comparator ) throws Exception { // create queue with numbers and basic comparator final PriorityQueue<Object> queue = new PriorityQueue<>(2, comparator); // stub data for replacement later queue.add(new BigInteger("1")); queue.add(new BigInteger("1")); // switch contents of queue final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue"); queueArray[ 0 ] = tgt; queueArray[ 1 ] = tgt; return queue; }
/** * Breadth-first search of graph. * @param v the start vertex. * @param cc the array to store the connected component id of vertices. * @param id the current component id. */ private void bfs(Visitor visitor, int v, int[] cc, int id) { visitor.visit(v); cc[v] = id; Queue<Integer> queue = new LinkedList<>(); queue.offer(v); while (!queue.isEmpty()) { int t = queue.poll(); for (Edge edge : graph[t]) { int i = edge.v2; if (!digraph && i == t) { i = edge.v1; } if (cc[i] == -1) { visitor.visit(i); queue.offer(i); cc[i] = id; } } } }
private void generateDescendants(Queue<Node> queue, int numOfNodes, final int maxNumberOfDescendants) { if (numOfNodes <= 0) { return; } Node parent = queue.poll(); if (parent == null) { return; } for (int i = 0; i < maxNumberOfDescendants; i++) { Node descendant = new Node(tracers.get(tracersRandom.nextInt(tracers.size())).tracingWrapper(), parent); queue.add(descendant); if (--numOfNodes <= 0) { return; } } generateDescendants(queue, numOfNodes, maxNumberOfDescendants); }
private void emitItem(GroupState<K, T> groupState, Object item) { Queue<Object> q = groupState.buffer; AtomicLong keyRequested = groupState.requested; REQUESTED.decrementAndGet(this); if (keyRequested == null || keyRequested.get() <= 0 || !(q == null || q.isEmpty())) { q.add(item); BUFFERED_COUNT.incrementAndGet(this); if (groupState.count.getAndIncrement() == 0) { pollQueue(groupState); } } else { nl.accept(groupState.getObserver(), item); if (keyRequested.get() != Long.MAX_VALUE) { keyRequested.decrementAndGet(); } } requestMoreIfNecessary(); }
public <E> void registerEventWithHandler(Class<E> eventClass, IEventHandler<?> handler){ synchronized (EVENT_LISTENERS) { if(!EVENT_LISTENERS.containsKey(eventClass)){ EVENT_LISTENERS.put(eventClass, new EventListenerCenter(handler, eventClass)); synchronized (QUEUED_LISTENERS) { if(QUEUED_LISTENERS.containsKey(eventClass)){ Queue<?> queue = QUEUED_LISTENERS.get(eventClass); for (Object object : queue) { EVENT_LISTENERS.get(eventClass).add(object); } QUEUED_LISTENERS.remove(eventClass); } } } } }
public <L> void registerToInterface(Class<L> interfaceClass, L listener) throws WrongListenerTypeException{ synchronized (EVENT_THROWERS) { if(EVENT_THROWERS.containsKey(interfaceClass)){ LinkedHashSet<IEventThrower<?>> list = EVENT_THROWERS.get(interfaceClass); for (IEventThrower<?> iEventThrower : list) { @SuppressWarnings("unchecked") IEventThrower<L> thrower = (IEventThrower<L>) iEventThrower; try{ thrower.subscribe(listener); }catch(ClassCastException e){ throw new WrongListenerTypeException(); } } }else{ if(QUEUED_LISTENERS.containsKey(interfaceClass)){ QUEUED_LISTENERS.get(interfaceClass).add(listener); }else{ Queue<Object> queue = new ArrayDeque<>(); queue.add(listener); QUEUED_LISTENERS.put(interfaceClass, queue); } } } }
public void echoTester(String path) throws Exception { WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, clientEndpointConfig, new URI("ws://localhost:" + getPort() + path)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText("Hello"); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); for (String message : messages) { Assert.assertEquals("Hello", message); } wsSession.close(); }
public void addChild(float x, float z, Observations obs, Map<Position, Position> map, Queue<Position> nextPos, Position currentPosition) { if (isFree(x, z, obs)) { Position child = new Position(x, z); if (!map.containsKey(child)) { map.put(child, currentPosition); nextPos.add(child); } } }
private void validateTupleNotInFailedSetButIsInFlight(DefaultRetryManager retryManager, MessageId messageId) { // Loop through all failed tuples for (Long key : retryManager.getFailedMessageIds().keySet()) { Queue queue = retryManager.getFailedMessageIds().get(key); assertFalse("Should not contain our messageId", queue.contains(messageId)); } assertTrue("Should be tracked as in flight", retryManager.getRetriesInFlight().contains(messageId)); }
public BindingUpdateThread(BindThreadUpdateExecutorService bindThreadUpdateExecutorService, DispatchThread dispatchThread, Queue<IUpdate> iUpdates, BlockingQueue<IUpdate> fetchUpdates) { super(dispatchThread, dispatchThread.getEventBus()); this.bindThreadUpdateExecutorService = bindThreadUpdateExecutorService; this.iUpdates = iUpdates; this.fetchUpdates = fetchUpdates; this.finishList = new ArrayList<IUpdate>(); }
public Test testsForArrayBlockingQueue() { return QueueTestSuiteBuilder.using( new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new ArrayBlockingQueue<String>(100, false, MinimalCollection.of(elements)); } }) .named("ArrayBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForArrayBlockingQueue()) .createTestSuite(); }
void runAll(Queue<CmdItem> queue) { synchronized (queue) { while (!queue.isEmpty()) { CmdItem cmdItem = queue.poll(); switch (cmdItem.cmdId) { case CMD_PROCESS_FRAME: processFrame((byte[]) cmdItem.param1, (Camera) cmdItem.param2); break; case CMD_SETUP_SURFACE_TEXTURE: setUpSurfaceTextureInternal((Camera) cmdItem.param1, (byte[]) cmdItem.param2); break; case CMD_SET_FILTER: setFilterInternal((GPUImageFilterGroupBase) cmdItem.param1); break; case CMD_RERUN_ONDRAW_RUNNABLE: ((Runnable) cmdItem.param1).run(); break; case CMD_RERUN_DRAWEND_RUNNABLE: ((Runnable) cmdItem.param1).run(); break; default: throw new RuntimeException("can't find command"); } cmdItem.param1 = cmdItem.param2 = null; mCmdItemCacher.cache(cmdItem); } } }
public void bfTraverse() { Queue<Node> q = new LinkedList<Node>(); q.add(r); while (!q.isEmpty()) { Node u = q.remove(); if (u.left != nil) q.add(u.left); if (u.right != nil) q.add(u.right); } }
public ExtendedPartitionedRegionQueryEvaluator(InternalDistributedSystem sys, PartitionedRegion pr, DefaultQuery query, Object[] parameters, SelectResults cumulativeResults, Set<Integer> bucketsToQuery, Queue<PartitionedQueryScenario> scenarios) { super(sys, pr, query, parameters, cumulativeResults, bucketsToQuery); this.scenarios = scenarios; extendedPRQueryProcessor = new ExtendedPRQueryProcessor(pr, query, null, new LinkedList(bucketsToQuery)); }
private boolean lookahead_0(ParserContext context, Token currentToken) { currentToken.detach(); Token token; Queue<Token> queue = new ArrayDeque<Token>(); boolean match = false; do { token = readToken(context); token.detach(); queue.add(token); if (false || match_ExamplesLine(context, token) ) { match = true; break; } } while (false || match_Empty(context, token) || match_Comment(context, token) || match_TagLine(context, token) ); context.tokenQueue.addAll(queue); return match; }
/** * Called from {@link Request#finish(String)}, indicating that processing of the given request * has finished. * * <p>Releases waiting requests for <code>request.getCacheKey()</code> if * <code>request.shouldCache()</code>.</p> */ <T> void finish(Request<T> request) { // Remove from the set of requests currently being processed. synchronized (mCurrentRequests) { mCurrentRequests.remove(request); } synchronized (mFinishedListeners) { for (RequestFinishedListener<T> listener : mFinishedListeners) { listener.onRequestFinished(request); } } if (request.shouldCache()) { synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey); if (waitingRequests != null) { if (VolleyLog.DEBUG) { VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.", waitingRequests.size(), cacheKey); } // Process all queued up requests. They won't be considered as in flight, but // that's not a problem as the cache has been primed by 'request'. mCacheQueue.addAll(waitingRequests); } } } }
@Test public void nowWithoutSpacesAndTime() { Queue<Token> words = parser.parse("now+03:04"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); }
/** * 绘制三条轨道上的敌方坦克 * @param canvas 默认画布 */ private void drawEnemyTank(Canvas canvas, int width) { mPaint.setColor(lModelColor); offsetETankX += enemySpeed; if (offsetETankX / enemyTankSpace == 1 || once) { offsetETankX = 0; once = false; } boolean isOverstep = false; int option = apperanceOption(); for (int i = 0; i < TANK_ROW_NUM; i++) { Queue<RectF> rectFQueue = eTankSparseArray.get(i); if (offsetETankX == 0 && i == option) { rectFQueue.offer(generateEnemyTank(i)); } for (RectF rectF : rectFQueue) { if (rectF.left >= width) { isOverstep = true; if (++overstepNum >= DEFAULT_TANK_MAGIC_TOTAL_NUM) { status = STATUS_GAME_OVER; break; } continue; } drawTank(canvas, rectF); } if (status == STATUS_GAME_OVER) break; if (isOverstep) { rectFQueue.poll(); isOverstep = false; } } invalidate(); }
/** * A deserialized/reserialized deque has same elements in same order */ public void testSerialization() throws Exception { Queue x = populatedDeque(SIZE); Queue y = serialClone(x); assertNotSame(x, y); assertEquals(x.size(), y.size()); assertEquals(x.toString(), y.toString()); assertTrue(Arrays.equals(x.toArray(), y.toArray())); while (!x.isEmpty()) { assertFalse(y.isEmpty()); assertEquals(x.remove(), y.remove()); } assertTrue(y.isEmpty()); }
@DatabaseExecutor private Queue<MessageId> getPendingDependents(Transaction txn, MessageId m) throws DbException { Queue<MessageId> pending = new LinkedList<MessageId>(); Map<MessageId, State> states = db.getMessageDependents(txn, m); for (Entry<MessageId, State> e : states.entrySet()) { if (e.getValue() == PENDING) pending.add(e.getKey()); } return pending; }
private void targetSetOnMouseDragged(ScreenMap target, MouseEvent e, Queue<GamePoint> newPath) { Point2D point = target.sceneToLocal(e.getSceneX(), e.getSceneY()); double mouseX = point.getX(); double mouseY = point.getY(); GamePoint coords = target.getCoordOfMouseHover(mouseX, mouseY); GamePoint actualGameLocation = target.getActualLocationOfSprite(coords); if (!coordAlreadyInPath(actualGameLocation, newPath)) { newPath.add(actualGameLocation); target.addBorderToCoordinate(coords); } e.consume(); }