• Post Reply Bookmark Topic Watch Topic
  • New Topic

Priority queue question?  RSS feed

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
When I run the below code I get a run time exception. Could you please see what could be wrong. Is this not correct use of poll() ? .
There is a similar example in Book for exam 310-065, generics and collections, Chapter 7




error that I get is

 
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you are iterating over most collections, you are not allowed to modify that collection except using the Iterator itself. Your code uses an Iterator as that is what the for-each loop actually does.
is nothing more than shorthand for Now, poll() will try to remove the first element, so that causes the exception.

It seems to me that you want to remove each element and then print it. If so you need to use an Iterator explicitly:
If you only want to print all the elements then you should just remove the call to i.remove(). In shorthand it will be even easier:
 
P Teng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob, that helps.

Meanwhile I have also found that the PriorityQueue is NOT thread safe. One can use PriorityBlockingQueue instead.

The earlier example if reworked as below works

 
Rob Spoor
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your original problem had nothing to do with thread safety since the looping and modification occurred in the same thread. Apparently PriorityBlockingQueue has found a way around this issue, probably by using a copy when iterating. (In fact, I have checked the source code of Java 6' PropertyBlockingQueue, and it indeed creates a copy of its data using toArray() around which it creates an Iterator.)

If you want to poll() all your elements you can also use a while-loop:
Because you're not using an Iterator this will not throw a ConcurrentModificationException.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!