Java Code Examples for java.util.Queue#peek()
The following examples show how to use
java.util.Queue#peek() .
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: BcastStreamingFinalReceiver.java From twister2 with Apache License 2.0 | 6 votes |
@Override protected boolean sendToTarget(int source, int target) { Queue<Object> values = readyToSend.get(target); if (values == null || values.isEmpty()) { return false; } // if we send this list successfully Object val = values.peek(); if (val == null) { return false; } while (val != null) { if (receiver.receive(target, val)) { values.poll(); val = values.peek(); } else { return false; } } return true; }
Example 2
Source File: Bot.java From jbot with GNU General Public License v3.0 | 6 votes |
/** * Invoke the appropriate method in a conversation. * * @param event received from facebook */ private void invokeChainedMethod(Event event) { Queue<MethodWrapper> queue = conversationQueueMap.get(event.getSender().getId()); if (queue != null && !queue.isEmpty()) { MethodWrapper methodWrapper = queue.peek(); try { EventType[] eventTypes = methodWrapper.getMethod().getAnnotation(Controller.class).events(); for (EventType eventType : eventTypes) { if (eventType.name().equalsIgnoreCase(event.getType().name())) { methodWrapper.getMethod().invoke(this, event); return; } } } catch (Exception e) { logger.error("Error invoking chained method: ", e); } } }
Example 3
Source File: PigstyMode.java From CatchPiggy with GNU General Public License v3.0 | 6 votes |
/** * 初始化小猪逃跑的路径, 根据data里面的数据来获取二维数组里面矩形坐标,从而拼成一条完整的逃跑路线 */ private MyPath initPath(Pig pig, List<WayData> data, int offsetX, int offsetY, boolean isPlayAnimation) { MyPath path = new MyPath(); Rect item = mItems[data.get(0).y][data.get(0).x]; if (isPlayAnimation) { path.moveTo(pig.getX(), pig.getY()); path.getData().remove(0); path.lineTo(item.left + offsetX, item.top + offsetY); } else { path.moveTo(item.left + offsetX, item.top + offsetY); } WayData removedItem = data.remove(0); Queue<WayData> queue = new ArrayDeque<>(data); while (!queue.isEmpty()) { item = mItems[queue.peek().y][queue.poll().x]; //队列中还有两个数据,则用quadTo,只有一条,就用lineTo if (!queue.isEmpty()) { Rect item2 = mItems[queue.peek().y][queue.poll().x]; path.quadTo(item.left + offsetX, item.top + offsetY, item2.left + offsetX, item2.top + offsetY); } else { path.lineTo(item.left + offsetX, item.top + offsetY); } } data.add(0, removedItem); return path; }
Example 4
Source File: KafkaOpenMetadataEventConsumer.java From egeria with Apache License 2.0 | 6 votes |
private boolean isFirstEventFullyProcessed(Queue<KafkaIncomingEvent> queue) { KafkaIncomingEvent firstEvent = queue.peek(); if (firstEvent == null) { //queue is empty return false; } //check whether the message processing timeout has elapsed (if there is one) if (messageProcessingTimeoutMs >= 0 && firstEvent.hasTimeElapsedSinceCreation(messageProcessingTimeoutMs)) { //max processing timeout has elapsed, treat the event as being fully processed log.warn("Processing of message at offset " + firstEvent.getOffset() + " timed out."); return true; } return firstEvent.isFullyProcessed(); }
Example 5
Source File: TestBase.java From thinr with Apache License 2.0 | 6 votes |
protected boolean doNextAsyncTaskRunBackgroundEvenIfCancelled(Queue<AsyncTaskHolder> asyncTasks) throws Exception { if (asyncTasks.size() > 0) { AsyncTaskHolder holder = asyncTasks.peek(); AsyncTask asyncTask = holder.asyncTask; Object res = Whitebox.invokeMethod(asyncTask, "doInBackground", holder.params); asyncTasks.poll(); if (holder.canceled) { Whitebox.invokeMethod(asyncTask, "onCancelled"); return false; } else { Whitebox.invokeMethod(asyncTask, "onPostExecute", res); } return true; } return false; }
Example 6
Source File: SerializedTaskExecutor.java From mldht with Mozilla Public License 2.0 | 5 votes |
public static <T> Consumer<T> runSerialized(Consumer<T> task) { AtomicBoolean lock = new AtomicBoolean(); Queue<T> q = new ConcurrentLinkedQueue<>(); Predicate<T> tryRun = (T toTry) -> { boolean success = false; while(lock.compareAndSet(false, true)) { try { if(toTry != null) { task.accept(toTry); success = true; } T other; while((other = q.poll()) != null) task.accept(other); } finally { lock.set(false); } if(q.peek() == null) break; } return success; }; return (T r) -> { // attempt to execute on current thread if(lock.get() == false && tryRun.test(r)) return;// success // execution on current thread failed, enqueue q.add(r); // try again in case other thread ceased draining the queue if (lock.get() == false) tryRun.test(null); }; }
Example 7
Source File: MeetingRooms2.java From LeetCode-Sol-Res with MIT License | 5 votes |
/** * Sort. Heap. Greedy. * Always put the next starting meeting after the first ending meeting. * If the start time overlaps with the nearest end time, need a new room. * So, sort the meetings according to start time first. * Then for each interval in the array: * | If min heap is not empty or start time doesn't overlap with first ending time: * | Poll first ending time from the heap. * | Add the ending time for current meeting. */ public int minMeetingRooms(Interval[] intervals) { if (intervals == null || intervals.length == 0) { return 0; } Arrays.sort(intervals, (i1, i2) -> i1.start - i2.start); Queue<Integer> firstEnd = new PriorityQueue<>(); for (Interval i : intervals) { if (!firstEnd.isEmpty() && i.start >= firstEnd.peek()) { firstEnd.poll(); } firstEnd.add(i.end); } return firstEnd.size(); }
Example 8
Source File: KReduceStreamingFinalReceiver.java From twister2 with Apache License 2.0 | 5 votes |
@Override public boolean progress() { boolean needsFurtherProgress = false; boolean sourcesFinished; for (int target : messages.keySet()) { if (batchDone.get(target)) { continue; } Queue<Object> targetSendQueue = sendQueue.get(target); sourcesFinished = isSourcesFinished(target); if (!sourcesFinished && !(dataFlowOperation.isDelegateComplete() && messages.get(target).isEmpty())) { needsFurtherProgress = true; } if (!targetSendQueue.isEmpty()) { Object current; while ((current = targetSendQueue.peek()) != null) { if (singularReceiver.receive(target, current)) { targetSendQueue.poll(); } } } if (sourcesFinished && dataFlowOperation.isDelegateComplete() && targetSendQueue.isEmpty()) { batchDone.put(target, true); } } return needsFurtherProgress; }
Example 9
Source File: SerializedTaskExecutor.java From bt with Apache License 2.0 | 5 votes |
public static <T> Consumer<T> runSerialized(Consumer<T> task) { AtomicBoolean lock = new AtomicBoolean(); Queue<T> q = new ConcurrentLinkedQueue<>(); Predicate<T> tryRun = (T toTry) -> { boolean success = false; while(lock.compareAndSet(false, true)) { try { if(toTry != null) { task.accept(toTry); success = true; } T other; while((other = q.poll()) != null) task.accept(other); } finally { lock.set(false); } if(q.peek() == null) break; } return success; }; return (T r) -> { // attempt to execute on current thread if(lock.get() == false && tryRun.test(r)) return;// success // execution on current thread failed, enqueue q.add(r); // try again in case other thread ceased draining the queue if (lock.get() == false) tryRun.test(null); }; }
Example 10
Source File: SingleConsumerQueueTest.java From caffeine with Apache License 2.0 | 5 votes |
@Test(dataProvider = "populated") public void removeElement_toEmpty(Queue<Integer> queue) { while (!queue.isEmpty()) { Integer value = queue.peek(); assertThat(queue.remove(value), is(true)); assertThat(queue.contains(value), is(false)); } assertThat(queue, is(deeplyEmpty())); }
Example 11
Source File: InternalCommand.java From AACAdditionPro with GNU General Public License v3.0 | 5 votes |
/** * Handle a command with certain arguments. * * @param sender the {@link CommandSender} that originally sent the command. * @param arguments a {@link Queue} which contains the remaining arguments. */ void invokeCommand(final CommandSender sender, final Queue<String> arguments) { // No permission is set or the sender has the permission if (!InternalPermission.hasPermission(sender, this.permission)) { ChatMessage.sendNoPermissionMessage(sender); return; } final String peek = arguments.peek(); if (peek != null) { // Command help if ("?".equals(peek)) { sendCommandHelp(sender); return; } final InternalCommand childCommand = this.childCommands.get(peek); if (childCommand != null) { // Remove the current command arg arguments.remove(); childCommand.invokeCommand(sender, arguments); return; } } // ------- Normal command procedure or childCommands is null or no fitting child commands were found. ------- // // Correct amount of arguments if (!this.commandAttributes.argumentsInRange(arguments.size())) { ChatMessage.sendErrorMessage(sender, "Wrong amount of arguments: " + arguments.size() + " expected: " + this.commandAttributes.getMinArguments() + " to " + this.commandAttributes.getMaxArguments()); return; } execute(sender, arguments); }
Example 12
Source File: VerboseCommand.java From AACAdditionPro with GNU General Public License v3.0 | 5 votes |
@Override protected void execute(Player sender, Queue<String> arguments) { final User user = UserManager.getUser(sender.getUniqueId()); if (user == null) { return; } boolean toggleTo = !UserManager.isVerbose(user); if (arguments.peek() != null) { switch (arguments.peek().toLowerCase()) { case "on": toggleTo = true; break; case "off": toggleTo = false; break; default: break; } } //Toggle mode UserManager.setVerbose(user, toggleTo); sendToggleMessage(sender, toggleTo); }
Example 13
Source File: SessionConversationAttributeStore.java From website with GNU Affero General Public License v3.0 | 5 votes |
/** * @param request * @param queue * @param attributeName */ private void pruneQueueIfNeeded(WebRequest request, Queue<String> queue, String attributeName) { // now check to see if we have hit the limit of conversations for the // command name. if (queue.size() > getNumConversationsToKeep()) { if (_logger.isDebugEnabled()) { for (Object str : queue.toArray()) { _logger.debug("pruneQueueIfNeeded - (" + attributeName + ") queue entry (" + str + " " + new java.util.Date(Long.parseLong((String)str))); } } // grab the next item to be removed. String conversationId = queue.peek(); if (conversationId != null) { _logger.debug("pruneQueueIfNeeded - (" + attributeName + ") removed (" + conversationId + " " + new java.util.Date( Long.parseLong(conversationId))); // remove the reference object from the session. removeEntityFromSession(request, attributeName, conversationId); } } }
Example 14
Source File: Connection.java From epoll with MIT License | 5 votes |
public boolean write(ByteBufferProvider bufferProvider) { Queue<ReadableData> queue = this.sending; if (queue == null) return true; while (!queue.isEmpty() && writer.compareAndSet(null, bufferProvider)) { try { ReadableData readable; while ((readable = queue.peek()) != null) { while (!readable.isComplete() && actualWrite(readable, bufferProvider)) { } if (!readable.isComplete()) return false; queue.poll(); readable.close(); readable.onComplete(); onWriteData(readable, !queue.isEmpty()); } } catch (Exception e) { e.printStackTrace(); close(); return false; } finally { writer.set(null); } } return true; }
Example 15
Source File: PrintTreesInLines.java From AtOffer with Apache License 2.0 | 5 votes |
public ArrayList<ArrayList<Integer>> print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(pRoot == null) { return res; } Queue<TreeNode> nodes = new LinkedList<>(); nodes.add(pRoot); ArrayList<Integer> currentLevel = new ArrayList<>(); int toBePrinted = 1; int nextLevel = 0; while(!nodes.isEmpty()) { TreeNode node = nodes.peek(); currentLevel.add(node.val); if(node.left != null) { nodes.add(node.left); nextLevel++; } if(node.right != null) { nodes.add(node.right); nextLevel++; } nodes.poll(); toBePrinted--; if(toBePrinted == 0) { res.add(new ArrayList<>(currentLevel)); currentLevel.clear(); toBePrinted = nextLevel; nextLevel = 0; } } return res; }
Example 16
Source File: WebSocketSession.java From mockwebserver with Apache License 2.0 | 5 votes |
private void send(Queue<WebSocketMessage> queue, String in) { if (queue != null && !queue.isEmpty()) { WebSocketMessage msg = queue.peek(); send(msg); if (msg.isToBeRemoved()) { queue.remove(); } checkIfShouldSendAgain(msg); checkIfShouldClose(); } else { webSocketRef.get().close(1002, "Unexpected message:" + in); } }
Example 17
Source File: SingleConsumerQueueTest.java From caffeine with Apache License 2.0 | 5 votes |
@Test(dataProvider = "populated") public void removeElement_whenFound(Queue<Integer> queue) { Integer first = queue.peek(); assertThat(queue.remove(first), is(true)); assertThat(queue, hasSize(POPULATED_SIZE - 1)); assertThat(queue.contains(first), is(false)); }
Example 18
Source File: FallbackServerSocket.java From webery with MIT License | 5 votes |
@Override public boolean write(ByteBufferProvider bufferProvider) { Queue<ReadableData> queue = this.sending; ReadableData readable; try { while ((readable = queue.peek()) != null) { while (!readable.isComplete() && actualWrite(readable, bufferProvider)) { } if (!readable.isComplete()) { key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); // System.out.println("key.interestOps(SelectionKey.OP_WRITE)"); return false; } queue.poll(); readable.close(); readable.onComplete(); boolean hasMore = !queue.isEmpty(); onWriteData(readable, hasMore); if (!hasMore && key.isValid()) { key.interestOps(SelectionKey.OP_READ); // System.out.println("key.interestOps(SelectionKey.OP_READ)"); } } // close(); } catch (Exception e) { e.printStackTrace(); IOTools.close(this); } return true; }
Example 19
Source File: TransitionDecoder.java From vn.vitk with GNU General Public License v3.0 | 4 votes |
/** * Derives a transition sequence from this dependency graph. This * is used to reconstruct the parsing process * @param graph a dependency graph * @param featureFrame * @return a list of labeled parsing context. */ public static List<ParsingContext> decode(DependencyGraph graph, FeatureFrame featureFrame) { List<ParsingContext> data = new ArrayList<ParsingContext>(); Stack<Integer> stack = new Stack<Integer>(); Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < graph.getSentence().length(); i++) queue.add(i); List<Dependency> currentArcs = new ArrayList<Dependency>(); FeatureExtractor featureBuilder = new FeatureExtractor(featureFrame); // the first transition is always a SHIFT Configuration config = new Configuration(graph.getSentence(), stack, queue); config = config.next("SH"); while (!config.isFinal()) { // extract feature strings List<String> features = featureBuilder.extract(config); StringBuilder text = new StringBuilder(); for (String f : features) { text.append(f); text.append(' '); } // determine the transition for this configuration Integer u = stack.peek(); Integer v = queue.peek(); String transition = ""; if (graph.hasArc(v, u)) { // LA transition = "LA-" + graph.getLabels()[u]; currentArcs.add(new Dependency(v, u, transition)); } else if (graph.hasArc(u, v)) { // RA transition = "RA-" + graph.getLabels()[v]; currentArcs.add(new Dependency(u, v, transition)); } else if (config.isReducible()) { transition = "RE"; } else { transition = "SH"; } // create a data point (a JavaBean) ParsingContext pc = new ParsingContext(); pc.setId(id); pc.setText(text.toString().trim()); pc.setTransition(transition); data.add(pc); id++; // proceed to the next configuration config = config.next(transition); } return data; }
Example 20
Source File: MultiThreadedWriterBase.java From hbase with Apache License 2.0 | 4 votes |
@Override public void run() { Thread.currentThread().setName(getClass().getSimpleName()); try { long expectedKey = startKey; Queue<Long> sortedKeys = new PriorityQueue<>(); while (expectedKey < endKey) { // Block until a new element is available. Long k; try { k = wroteKeys.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.info("Inserted key tracker thread interrupted", e); break; } if (k == null) { continue; } if (k == expectedKey) { // Skip the "sorted key" queue and consume this key. wroteUpToKey.set(k); ++expectedKey; } else { sortedKeys.add(k); } // See if we have a sequence of contiguous keys lined up. while (!sortedKeys.isEmpty() && ((k = sortedKeys.peek()) == expectedKey)) { sortedKeys.poll(); wroteUpToKey.set(k); ++expectedKey; } wroteKeyQueueSize.set(wroteKeys.size() + sortedKeys.size()); } } catch (Exception ex) { LOG.error("Error in inserted/updaed key tracker", ex); } finally { numThreadsWorking.decrementAndGet(); } }