How to remove elements from a queue in Java with a loop -
How to remove elements from a queue in Java with a loop -
i have info construction this:
blockingqueue mailbox = new linkedblockingqueue();
i'm trying this:
for(mail mail: mailbox) { if(badnews(mail)) { mailbox.remove(mail); } }
obviously contents of loop interfere bounds , error triggered, this:
for(int = 0; < mailbox.size(); i++) { if(badnews(mailbox.get(i))) { mailbox.remove(i); i--; } }
but sadly blockingqueue's don't have function or remove element index, i'm stuck. ideas?
edit - few clarifications: 1 of goals maintain same ordering popping head , putting tail no good. also, although no other threads remove mail service mailbox, add together it, don't want in middle of removal algorithm, have send me mail, , have exception occur.
thanks in advance!
you may p̶o̶p̶ poll
, p̶u̶s̶h̶ offer
elements in queue until create finish loop on queue. here's example:
mail firstmail = mailbox.peek(); mail service currentmail = mailbox.pop(); while (true) { //a base of operations status stop loop mail service tempmail = mailbox.peek(); if (tempmail == null || tempmail.equals(firstmail)) { mailbox.offer(currentmail); break; } //if there's nil wrong current mail, re add together mailbox if (!badnews(currentmail)) { mailbox.offer(currentmail); } currentmail = mailbox.poll(); }
note approach work if code executed in single thread , there's no other thread removes items queue.
maybe need check if want poll or take elements blockingqueue. similar offer , put.
more info:
java blockingqueue take() vs poll() linkedblockingqueue set vs offeranother less buggy approach using temporary collection, not concurrent, , store elements still need in queue. here's kickoff example:
list<mail> maillisttemp = new arraylist<>(); while (mailbox.peek() != null) { mail service mail = mailbox.take(); if (!badnews(mail)) { maillisttemp.add(mail); } } (mail mail service : maillisttemp) { mailbox.offer(mail); }
java loops blockingqueue
Comments
Post a Comment