List of usage examples for java.util Deque poll
E poll();
From source file:Main.java
public static void main(String[] args) { Deque<Integer> deque = new ArrayDeque<Integer>(8); deque.add(1);/*from w w w . j a va 2s . c om*/ deque.add(2); deque.add(3); deque.add(4); System.out.println(deque); int retval = deque.poll(); System.out.println("Element removed is " + retval); System.out.println(deque); }
From source file:com.epam.reportportal.jbehave.JBehaveUtils.java
/** * Iterate over started test items cache and remove all not finished item * * @param status//from w w w.j a v a 2s. co m */ public static void makeSureAllItemsFinished(String status) { if (RP_IS_DOWN.get()) { return; } Deque<String> items = JBehaveContext.getItemsCache(); String item; while (null != (item = items.poll())) { FinishTestItemRQ rq = new FinishTestItemRQ(); rq.setEndTime(Calendar.getInstance().getTime()); rq.setStatus(status); try { reportPortalService.get().finishTestItem(item, rq); } catch (Exception e) { LOGGER.error("Unable to finish started test items in ReportPortal", e); } } }
From source file:com.google.uzaygezen.core.MapNode.java
/** * For testing purposes only.// w w w . ja v a2s. c o m * * @return the full preorder list of nodes of this subtree */ public List<MapNode<K, V>> preorder() { List<MapNode<K, V>> list = Lists.newArrayList(); Deque<MapNode<K, V>> stack = new ArrayDeque<MapNode<K, V>>(); stack.push(this); MapNode<K, V> node; while ((node = stack.poll()) != null) { list.add(node); for (MapNode<K, V> child : node.children.values()) { stack.push(child); } } return list; }
From source file:com.google.uzaygezen.core.MapNode.java
/** * For testing purposes only.//from w ww .j a va 2s . c o m * * @return the number of nodes in the subtree rooted in this node and the * number of leaves. */ int[] subtreeSizeAndLeafCount() { Deque<MapNode<K, V>> stack = new ArrayDeque<MapNode<K, V>>(); stack.push(this); MapNode<K, V> node; int size = 0; int leafCount = 0; while ((node = stack.poll()) != null) { ++size; if (node.children.isEmpty()) { ++leafCount; } for (MapNode<K, V> child : node.children.values()) { stack.push(child); } } return new int[] { size, leafCount }; }
From source file:eu.openanalytics.rsb.rservi.CircularRServiUriSelector.java
private URI getCircular(final Deque<URI> applicationRserviPoolUris) { if (applicationRserviPoolUris.size() == 1) { return applicationRserviPoolUris.peek(); }//from ww w .ja va2s.c o m synchronized (applicationRserviPoolUris) { final URI uri = applicationRserviPoolUris.poll(); applicationRserviPoolUris.add(uri); return uri; } }
From source file:monasca.persister.repository.cassandra.CassandraMetricRepo.java
@Override public int flush(String id) throws RepoException { long startTime = System.nanoTime(); List<ResultSetFuture> results = new ArrayList<>(); List<Deque<BatchStatement>> list = batches.getAllBatches(); for (Deque<BatchStatement> q : list) { BatchStatement b;//from w w w .ja v a2 s .c o m while ((b = q.poll()) != null) { results.add(session.executeAsync(b)); } } List<ListenableFuture<ResultSet>> futures = Futures.inCompletionOrder(results); boolean cancel = false; Exception ex = null; for (ListenableFuture<ResultSet> future : futures) { if (cancel) { future.cancel(false); continue; } try { future.get(); } catch (InterruptedException | ExecutionException e) { cancel = true; ex = e; } } this.commitTimer.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); if (ex != null) { metricFailed.inc(metricCount); throw new RepoException(ex); } batches.clear(); int flushCnt = metricCount; metricCount = 0; metricCompleted.inc(flushCnt); return flushCnt; }
From source file:com.google.uzaygezen.core.Pow2LengthBitSetRangeFactory.java
@Override public Map<Pow2LengthBitSetRange, NodeValue<V>> apply(MapNode<BitVector, V> from) { if (from == null) { return ImmutableMap.of(); }/* ww w . j a v a2s.c o m*/ Deque<MapNode<BitVector, V>> inputStack = new ArrayDeque<MapNode<BitVector, V>>(); Deque<BitVectorWithIterationLevelAndValue> outputStack = new ArrayDeque<BitVectorWithIterationLevelAndValue>(); inputStack.push(from); int n = elementLengthSums.length; int bitCount = n == 0 ? 0 : elementLengthSums[n - 1]; outputStack.push(new BitVectorWithIterationLevelAndValue(BitVectorFactories.OPTIMAL.apply(bitCount), n, from.getValue())); MapNode<BitVector, V> inputNode; Map<Pow2LengthBitSetRange, NodeValue<V>> map = Maps.newHashMap(); while ((inputNode = inputStack.poll()) != null) { BitVectorWithIterationLevelAndValue outputElement = outputStack.poll(); map.put(new Pow2LengthBitSetRange(outputElement.bitVector, outputElement.level == 0 ? 0 : elementLengthSums[outputElement.level - 1]), NodeValue.of(outputElement.value, inputNode.getChildren().isEmpty())); Preconditions.checkArgument( outputElement.level > 0 || (inputNode.getChildren().isEmpty() && outputElement.level >= 0)); for (Entry<BitVector, MapNode<BitVector, V>> entry : inputNode.getChildren().entrySet()) { inputStack.push(entry.getValue()); BitVector childBitSet = outputElement.bitVector.clone(); BitVector key = entry.getKey(); for (int i = key.size() == 0 ? -1 : key.nextSetBit(0); i != -1; i = i == key.size() - 1 ? -1 : key.nextSetBit(i + 1)) { int bitIndex = (outputElement.level == 1 ? 0 : elementLengthSums[outputElement.level - 2]) + i; Preconditions.checkState(bitIndex < bitCount, "bitIndex is too high"); Preconditions.checkState(!childBitSet.get(bitIndex)); childBitSet.set(bitIndex); } outputStack.push(new BitVectorWithIterationLevelAndValue(childBitSet, outputElement.level - 1, entry.getValue().getValue())); } } Preconditions.checkState(outputStack.isEmpty() & !map.isEmpty()); return map; }
From source file:com.spotify.helios.agent.QueueingHistoryWriter.java
private TaskStatusEvent getNext() { // Some explanation: We first find the eldest event from amongst the queues (ok, they're // deques, but we really use it as a put back queue), and only then to we try to get // a lock on the relevant queue from whence we got the event. Assuming that all worked // *and* that the event we have wasn't rolled off due to max-size limitations, we then // pull the item off the queue and return it. We're basically doing optimistic concurrency, // and skewing things so that adding to this should be cheap. while (true) { final TaskStatusEvent current = findEldestEvent(); // Didn't find anything that needed processing? if (current == null) { return null; }//from w ww .ja v a2s. c om final JobId id = current.getStatus().getJob().getId(); final Deque<TaskStatusEvent> deque = items.get(id); if (deque == null) { // shouldn't happen because we should be the only one pulling items off, but.... continue; } synchronized (deque) { if (!deque.peek().equals(current)) { // item got rolled off, try again continue; } // Pull it off the queue and be paranoid. final TaskStatusEvent newCurrent = deque.poll(); count.decrementAndGet(); checkState(current.equals(newCurrent), "current should equal newCurrent"); // Safe because this is the *only* place we hold these two locks at the same time. synchronized (items) { // Extra paranoia: curDeque should always == deque final Deque<TaskStatusEvent> curDeque = items.get(id); if (curDeque != null && curDeque.isEmpty()) { items.remove(id); } } return current; } } }
From source file:com.spotify.helios.client.DefaultRequestDispatcher.java
/** * Sets up a connection, retrying on connect failure. *//*from ww w. ja v a 2 s .c o m*/ private HttpURLConnection connect(final URI uri, final String method, final byte[] entity, final Map<String, List<String>> headers) throws URISyntaxException, IOException, TimeoutException, InterruptedException, HeliosException { final long deadline = currentTimeMillis() + RETRY_TIMEOUT_MILLIS; final int offset = ThreadLocalRandom.current().nextInt(); while (currentTimeMillis() < deadline) { final List<URI> endpoints = endpointSupplier.get(); if (endpoints.isEmpty()) { throw new RuntimeException("failed to resolve master"); } log.debug("endpoint uris are {}", endpoints); // Resolve hostname into IPs so client will round-robin and retry for multiple A records. // Keep a mapping of IPs to hostnames for TLS verification. final List<URI> ipEndpoints = Lists.newArrayList(); final Map<URI, URI> ipToHostnameUris = Maps.newHashMap(); for (final URI hnUri : endpoints) { try { final InetAddress[] ips = InetAddress.getAllByName(hnUri.getHost()); for (final InetAddress ip : ips) { final URI ipUri = new URI(hnUri.getScheme(), hnUri.getUserInfo(), ip.getHostAddress(), hnUri.getPort(), hnUri.getPath(), hnUri.getQuery(), hnUri.getFragment()); ipEndpoints.add(ipUri); ipToHostnameUris.put(ipUri, hnUri); } } catch (UnknownHostException e) { log.warn("Unable to resolve hostname {} into IP address: {}", hnUri.getHost(), e); } } for (int i = 0; i < ipEndpoints.size() && currentTimeMillis() < deadline; i++) { final URI ipEndpoint = ipEndpoints.get(positive(offset + i) % ipEndpoints.size()); final String fullpath = ipEndpoint.getPath() + uri.getPath(); final String scheme = ipEndpoint.getScheme(); final String host = ipEndpoint.getHost(); final int port = ipEndpoint.getPort(); if (!VALID_PROTOCOLS.contains(scheme) || host == null || port == -1) { throw new HeliosException(String.format( "Master endpoints must be of the form \"%s://heliosmaster.domain.net:<port>\"", VALID_PROTOCOLS_STR)); } final URI realUri = new URI(scheme, host + ":" + port, fullpath, uri.getQuery(), null); AgentProxy agentProxy = null; Deque<Identity> identities = Queues.newArrayDeque(); try { if (scheme.equals("https")) { agentProxy = AgentProxies.newInstance(); for (final Identity identity : agentProxy.list()) { if (identity.getPublicKey().getAlgorithm().equals("RSA")) { // only RSA keys will work with our TLS implementation identities.offerLast(identity); } } } } catch (Exception e) { log.warn("Couldn't get identities from ssh-agent", e); } try { do { final Identity identity = identities.poll(); try { log.debug("connecting to {}", realUri); final HttpURLConnection connection = connect0(realUri, method, entity, headers, ipToHostnameUris.get(ipEndpoint).getHost(), agentProxy, identity); final int responseCode = connection.getResponseCode(); if (((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED)) && !identities.isEmpty()) { // there was some sort of security error. if we have any more SSH identities to try, // retry with the next available identity log.debug("retrying with next SSH identity since {} failed", identity.getComment()); continue; } return connection; } catch (ConnectException | SocketTimeoutException | UnknownHostException e) { // UnknownHostException happens if we can't resolve hostname into IP address. // UnknownHostException's getMessage method returns just the hostname which is a // useless message, so log the exception class name to provide more info. log.debug(e.toString()); // Connecting failed, sleep a bit to avoid hammering and then try another endpoint Thread.sleep(200); } } while (false); } finally { if (agentProxy != null) { agentProxy.close(); } } } log.warn("Failed to connect, retrying in 5 seconds."); Thread.sleep(5000); } throw new TimeoutException("Timed out connecting to master"); }
From source file:com.skelril.skree.content.world.wilderness.WildernessWorldWrapper.java
private PlayerCombatParser createFor(Cancellable event, int level) { return new PlayerCombatParser() { @Override/*from w ww . j a va 2 s. c om*/ public void processPvP(Player attacker, Player defender) { if (allowsPvP(level)) { return; } Optional<PvPService> optService = Sponge.getServiceManager().provide(PvPService.class); if (optService.isPresent()) { PvPService service = optService.get(); if (service.getPvPState(attacker).allowByDefault() && service.getPvPState(defender).allowByDefault()) { return; } } attacker.sendMessage(Text.of(TextColors.RED, "PvP is opt-in only in this part of the Wilderness!")); attacker.sendMessage( Text.of(TextColors.RED, "Mandatory PvP is from level ", getFirstPvPLevel(), " and on.")); event.setCancelled(true); } @Override public void processMonsterAttack(Living attacker, Player defender) { if (!(event instanceof DamageEntityEvent)) { return; } DamageEntityEvent dEvent = (DamageEntityEvent) event; // If they're endermites they hit through armor, otherwise they get a damage boost if (attacker.getType() == EntityTypes.ENDERMITE) { for (Tuple<DamageModifier, Function<? super Double, Double>> modifier : dEvent.getModifiers()) { dEvent.setDamage(modifier.getFirst(), (a) -> 0D); } dEvent.setBaseDamage(1); } else { dEvent.setBaseDamage(dEvent.getBaseDamage() + getDamageMod(level)); } // Only apply scoring while in survival mode if (defender.get(Keys.GAME_MODE).orElse(GameModes.SURVIVAL) != GameModes.SURVIVAL) { return; } WildernessPlayerMeta meta = playerMetaMap.get(defender.getUniqueId()); if (meta != null) { meta.hit(); } } @Override public void processPlayerAttack(Player attacker, Living defender) { Task.builder().delayTicks(1) .execute(() -> healthPrinter.print(MessageChannel.fixed(attacker), defender)) .submit(SkreePlugin.inst()); if (!(defender instanceof Monster) || defender instanceof Creeper) { return; } // Only apply scoring while in survival mode if (attacker.get(Keys.GAME_MODE).orElse(GameModes.SURVIVAL) != GameModes.SURVIVAL) { return; } WildernessPlayerMeta meta = playerMetaMap.get(attacker.getUniqueId()); if (meta != null) { meta.attack(); if (meta.getRatio() > 30 && meta.getFactors() > 35) { Deque<Entity> spawned = new ArrayDeque<>(); for (int i = Probability.getRandom(5); i > 0; --i) { Entity entity = attacker.getWorld().createEntity(EntityTypes.ENDERMITE, defender.getLocation().getPosition()); entity.getWorld().spawnEntity(entity, Cause.source(SpawnCause.builder().type(SpawnTypes.PLUGIN).build()).build()); spawned.add(entity); } IntegratedRunnable runnable = new IntegratedRunnable() { @Override public boolean run(int times) { Entity mob = spawned.poll(); if (mob.isLoaded() && mob.getWorld().equals(attacker.getWorld())) { mob.setLocation(attacker.getLocation()); } return true; } @Override public void end() { } }; TimedRunnable timedRunnable = new TimedRunnable<>(runnable, spawned.size()); timedRunnable.setTask(Task.builder().execute(timedRunnable).delayTicks(40).intervalTicks(20) .submit(SkreePlugin.inst())); } if (System.currentTimeMillis() - meta.getLastReset() >= TimeUnit.MINUTES.toMillis(5)) { meta.reset(); } } } }; }