java.util.Queue#peek ( )源码实例Demo

下面列出了java.util.Queue#peek ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: twister2   文件: BcastStreamingFinalReceiver.java
@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;
}
 
源代码2 项目: thinr   文件: TestBase.java
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;
}
 
源代码3 项目: egeria   文件: KafkaOpenMetadataEventConsumer.java
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();
}
 
源代码4 项目: CatchPiggy   文件: PigstyMode.java
/**
 * 初始化小猪逃跑的路径, 根据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;
}
 
源代码5 项目: jbot   文件: Bot.java
/**
 * 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);
        }
    }
}
 
/**
 * @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);
        }
    }
}
 
源代码7 项目: caffeine   文件: SingleConsumerQueueTest.java
@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()));
}
 
源代码8 项目: bt   文件: SerializedTaskExecutor.java
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);
		
	};
}
 
源代码9 项目: mldht   文件: SerializedTaskExecutor.java
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);
		
	};
}
 
源代码10 项目: LeetCode-Sol-Res   文件: MeetingRooms2.java
/**
 * 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();
}
 
源代码11 项目: twister2   文件: KReduceStreamingFinalReceiver.java
@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;
}
 
源代码12 项目: AACAdditionPro   文件: InternalCommand.java
/**
 * 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);
}
 
源代码13 项目: AACAdditionPro   文件: VerboseCommand.java
@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);
}
 
源代码14 项目: epoll   文件: Connection.java
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;
}
 
源代码15 项目: AtOffer   文件: PrintTreesInLines.java
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;
}
 
源代码16 项目: mockwebserver   文件: WebSocketSession.java
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);
    }
}
 
源代码17 项目: caffeine   文件: SingleConsumerQueueTest.java
@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));
}
 
源代码18 项目: webery   文件: FallbackServerSocket.java
@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;
        }
 
源代码19 项目: vn.vitk   文件: TransitionDecoder.java
/**
 * 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;
}
 
源代码20 项目: hbase   文件: MultiThreadedWriterBase.java
@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();
  }
}