Java Code Examples for java.util.Queue#iterator()

The following examples show how to use java.util.Queue#iterator() . 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: ConcurrentEvictingQueueGeneralTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void iteratorModificationAdd() throws Exception {
    Queue<Integer> queue = new ConcurrentEvictingQueue<>(2);
    queue.addAll(asList(4, 5));
    Iterator<Integer> iterator = queue.iterator();

    queue.peek();

    assertThat(iterator.hasNext()).isTrue();
    Integer first = iterator.next();
    assertThat(first).isEqualTo(4);

    queue.add(6);
    assertThat(iterator.hasNext()).isTrue();

    exception.expect(ConcurrentModificationException.class);
    iterator.next();
}
 
Example 2
Source File: MOAT.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
private static void testQueueIteratorRemove(Queue<Integer> q) {
    System.err.printf("testQueueIteratorRemove %s%n",
                      q.getClass().getSimpleName());
    q.clear();
    for (int i = 0; i < 5; i++)
        q.add(i);
    Iterator<Integer> it = q.iterator();
    check(it.hasNext());
    for (int i = 3; i >= 0; i--)
        q.remove(i);
    equal(it.next(), 0);
    equal(it.next(), 4);

    q.clear();
    for (int i = 0; i < 5; i++)
        q.add(i);
    it = q.iterator();
    equal(it.next(), 0);
    check(it.hasNext());
    for (int i = 1; i < 4; i++)
        q.remove(i);
    equal(it.next(), 1);
    equal(it.next(), 4);
}
 
Example 3
Source File: StreamEventBuffer.java    From java-dcp-client with Apache License 2.0 6 votes vote down vote up
/**
 * Discard any buffered events in the given vBucket with sequence numbers
 * higher than the given sequence number.
 */
private void rollback(final short vbucket, final long toSeqno) {
  final Queue<BufferedEvent> queue = partitionQueues.get(vbucket);

  synchronized (queue) {
    for (Iterator<BufferedEvent> i = queue.iterator(); i.hasNext(); ) {
      final BufferedEvent event = i.next();
      final boolean eventSeqnoIsGreaterThanRollbackSeqno = Long.compareUnsigned(event.seqno, toSeqno) > 0;
      if (eventSeqnoIsGreaterThanRollbackSeqno) {
        LOGGER.trace("Dropping event with seqno {} from stream buffer for partition {}", event.seqno, vbucket);
        event.discard();
        i.remove();
      }
    }
  }
}
 
Example 4
Source File: SmallPriorityQueueTest.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected=NoSuchElementException.class)
public void testIteratorOutOfBounds() {
	Queue<Integer> q = PriorityQueue.of(universe1);
	
	Iterator<Integer> it = q.iterator();
	
	while (it.hasNext()) {
		it.next();
	}
	it.next();
}
 
Example 5
Source File: SingleConsumerQueueTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "populated")
public void iterator_removal_toEmpty(Queue<Integer> queue) {
  for (Iterator<Integer> it = queue.iterator(); it.hasNext();) {
    it.next();
    it.remove();
  }
  assertThat(queue, is(deeplyEmpty()));
}
 
Example 6
Source File: AbstractScheduledEventExecutor.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
void purgeCancelledScheduledTasks() {
    Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue;
    if (isNullOrEmpty(scheduledTaskQueue)) {
        return;
    }
    Iterator<ScheduledFutureTask<?>> i = scheduledTaskQueue.iterator();
    while (i.hasNext()) {
        ScheduledFutureTask<?> task = i.next();
        if (task.isCancelled()) {
            i.remove();
        }
    }
}
 
Example 7
Source File: SingleConsumerQueueTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "populated", expectedExceptions = IllegalStateException.class)
public void iterator_removal_duplicate(Queue<Integer> queue) {
  Iterator<Integer> it = queue.iterator();
  it.next();
  it.remove();
  it.remove();
}
 
Example 8
Source File: SelectEvent.java    From jason with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Event selectEvent(Queue<Event> events) {
    Iterator<Event> ie = events.iterator();
    while (ie.hasNext()) {
        un.clear();
        Event e = ie.next();
        if (un.unifies(gold, e.getTrigger()) || un.unifies(restart, e.getTrigger())) {
            //getTS().getLogger().info("custom select event "+e);
            ie.remove();
            return e;
        }
    }
    return super.selectEvent(events);
}
 
Example 9
Source File: SmallPriorityQueueTest.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected=IllegalStateException.class)
public void testIteratorDoubleRemove() {
	Queue<Integer> q = PriorityQueue.of(universe1);
	
	Iterator<Integer> it = q.iterator();
	
	while (it.hasNext()) {
		it.next();
		it.remove();
		it.remove();
	}
}
 
Example 10
Source File: SmallPriorityQueueTest.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIteratorRemove() {
	Queue<Integer> q = PriorityQueue.of(universe1);
	
	Iterator<Integer> it = q.iterator();
	
	while (it.hasNext()) {
		Integer i = it.next();
		assertTrue(q.contains(i));
		it.remove();
		assertFalse(q.contains(i));
	}
}
 
Example 11
Source File: PodReplicationController.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
public void undeployPods(String domain) {
	systemLogger().info(String.format("[REPLICATION] Domain '%s' undeploying", domain));
	
	Queue<UUID> queue = system.getPodDomains().get(domain);
	Iterator<UUID> iterator = queue.iterator();
	while (iterator.hasNext()) {
		UUID id = iterator.next();
		systemLogger().info(String.format("[REPLICATION] PodActor (%s, %s) stopping", domain, id));
		system.send(new ActorMessage<>(null, STOP, system.SYSTEM_ID, id));
		iterator.remove();
	}
	system.getPodDomains().remove(domain);
}
 
Example 12
Source File: RedissonPriorityQueueTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void checkIterator(Queue<Integer> set, Queue<Integer> setCopy) {
    for (Iterator<Integer> iterator = set.iterator(); iterator.hasNext();) {
        Integer value = iterator.next();
        if (!setCopy.remove(value)) {
            Assert.fail();
        }
    }

    Assert.assertEquals(0, setCopy.size());
}
 
Example 13
Source File: AvailableCommands.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, Direction direction, ProtocolVersion protocolVersion) {
  int commands = ProtocolUtils.readVarInt(buf);
  WireNode[] wireNodes = new WireNode[commands];
  for (int i = 0; i < commands; i++) {
    wireNodes[i] = deserializeNode(buf, i);
  }

  // Iterate over the deserialized nodes and attempt to form a graph. We also resolve any cycles
  // that exist.
  Queue<WireNode> nodeQueue = new ArrayDeque<>(Arrays.asList(wireNodes));
  while (!nodeQueue.isEmpty()) {
    boolean cycling = false;

    for (Iterator<WireNode> it = nodeQueue.iterator(); it.hasNext(); ) {
      WireNode node = it.next();
      if (node.toNode(wireNodes)) {
        cycling = true;
        it.remove();
      }
    }

    if (!cycling) {
      // Uh-oh. We can't cycle. This is bad.
      throw new IllegalStateException("Stopped cycling; the root node can't be built.");
    }
  }

  int rootIdx = ProtocolUtils.readVarInt(buf);
  rootNode = (RootCommandNode<Object>) wireNodes[rootIdx].built;
}
 
Example 14
Source File: TestExecutor.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Nullable
private static boolean executeOne(Queue<RunnableWrapper> tasks, AtomicInteger taskCount) {
    Iterator<RunnableWrapper> i = tasks.iterator();
    if (i.hasNext()) {
        final Runnable task = i.next();
        i.remove();
        taskCount.incrementAndGet();
        task.run();
        return true;
    }
    return false;
}
 
Example 15
Source File: SingleConsumerQueueTest.java    From caffeine with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "populated")
public void iterator_removal(Queue<Integer> queue) {
  Iterator<Integer> it = queue.iterator();
  it.next();
  it.remove();
}
 
Example 16
Source File: MetricsUtil.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
/**
 * Calculates the durations between the START and STOP snapshots per metric description and subject (if any)
 *
 * @param logChannelId
 *          the id of the log channel to investigate
 * @return the duration in ms
 */
public static List<MetricsDuration> getDurations( String logChannelId ) {
  Map<String, MetricsSnapshotInterface> last = new HashMap<String, MetricsSnapshotInterface>();
  Map<String, MetricsDuration> map = new HashMap<String, MetricsDuration>();

  Queue<MetricsSnapshotInterface> metrics = MetricsRegistry.getInstance().getSnapshotList( logChannelId );

  Iterator<MetricsSnapshotInterface> iterator = metrics.iterator();
  while ( iterator.hasNext() ) {
    MetricsSnapshotInterface snapshot = iterator.next();

    // Do we have a start point in the map?
    //
    String key =
      snapshot.getMetric().getDescription()
        + ( snapshot.getSubject() == null ? "" : ( " - " + snapshot.getSubject() ) );
    MetricsSnapshotInterface lastSnapshot = last.get( key );
    if ( lastSnapshot == null ) {
      lastSnapshot = snapshot;
      last.put( key, lastSnapshot );
    } else {
      // If we have a START-STOP range, calculate the duration and add it to the duration map...
      //
      MetricsInterface metric = lastSnapshot.getMetric();
      if ( metric.getType() == MetricsSnapshotType.START
        && snapshot.getMetric().getType() == MetricsSnapshotType.STOP ) {
        long extraDuration = snapshot.getDate().getTime() - lastSnapshot.getDate().getTime();

        MetricsDuration metricsDuration = map.get( key );
        if ( metricsDuration == null ) {
          metricsDuration =
            new MetricsDuration(
              lastSnapshot.getDate(), metric.getDescription(), lastSnapshot.getSubject(), logChannelId,
              extraDuration );
        } else {
          metricsDuration.setDuration( metricsDuration.getDuration() + extraDuration );
          metricsDuration.incrementCount();
          if ( metricsDuration.getEndDate().getTime() < snapshot.getDate().getTime() ) {
            metricsDuration.setEndDate( snapshot.getDate() );
          }
        }
        map.put( key, metricsDuration );
      }
    }
  }

  return new ArrayList<MetricsDuration>( map.values() );
}
 
Example 17
Source File: PriorityQueueSort.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    int n = 10000;
    if (args.length > 0)
        n = Integer.parseInt(args[0]);

    List<Integer> sorted = new ArrayList<>(n);
    for (int i = 0; i < n; i++)
        sorted.add(new Integer(i));
    List<Integer> shuffled = new ArrayList<>(sorted);
    Collections.shuffle(shuffled);

    Queue<Integer> pq = new PriorityQueue<>(n, new MyComparator());
    for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); )
        pq.add(i.next());

    List<Integer> recons = new ArrayList<>();
    while (!pq.isEmpty())
        recons.add(pq.remove());
    if (!recons.equals(sorted))
        throw new RuntimeException("Sort test failed");

    recons.clear();
    pq = new PriorityQueue<>(shuffled);
    while (!pq.isEmpty())
        recons.add(pq.remove());
    if (!recons.equals(sorted))
        throw new RuntimeException("Sort test failed");

    // Remove all odd elements from queue
    pq = new PriorityQueue<>(shuffled);
    for (Iterator<Integer> i = pq.iterator(); i.hasNext(); )
        if ((i.next().intValue() & 1) == 1)
            i.remove();
    recons.clear();
    while (!pq.isEmpty())
        recons.add(pq.remove());

    for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); )
        if ((i.next().intValue() & 1) == 1)
            i.remove();

    if (!recons.equals(sorted))
        throw new RuntimeException("Iterator remove test failed.");
}
 
Example 18
Source File: RedBlackTree.java    From algorithms with MIT License 4 votes vote down vote up
public Iterator<K> iterator() {
    Queue<K> keys = new ArrayDeque<K>();
    inorder(keys, root);
    return keys.iterator();
}
 
Example 19
Source File: BST.java    From algorithms with MIT License 4 votes vote down vote up
public Iterator<K> iterator() {
    Queue<K> keys = new ArrayDeque<K>();
    inorder(keys, root);
    return keys.iterator();
}
 
Example 20
Source File: TaskQueueThread.java    From AcDisplay with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run() {
    Timber.tag(TAG).d("Starting thread...");
    super.run();

    Queue<T> queue = new ConcurrentLinkedQueue<>();
    while (mRunning) {
        synchronized (this) {
            if (mQueue.isEmpty())
                try {
                    // Wait for a next #sendEvent(Event),
                    // where this thread will be unlocked.
                    mWaiting = true;
                    wait();
                } catch (InterruptedException ignored) {
                } finally {
                    mWaiting = false;
                }

            // Move all pending events to a local copy, so we don't need
            // to block main queue.
            while (!mQueue.isEmpty()) {
                queue.add(mQueue.poll());
            }
        }

        if (isLost()) {
            mRunning = false;
            break;
        }

        Iterator<T> iterator = queue.iterator();
        while (iterator.hasNext()) {
            T object = iterator.next();
            // ~~
            onHandleTask(object);
            // ~~
            iterator.remove();
        }
    }


    Timber.tag(TAG).d("Stopping thread...");
}