• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Peter Rooke
  • Himai Minh
Bartenders:
  • Piet Souris
  • Mikalai Zaikin

ConcurrentModificationException and for loops

 
Ranch Hand
Posts: 384
MyEclipse IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For given code



The following code does not throw ConcurrentModificationException and run fine , I perfectly understand as ConcurrentModificationException is thrown when a thread iterating over it AND modifying it.
By iterating I means specifically using Iterator not using for loops






But here , it throws ConcurrentModificationException. I dont know why ?






Regards
naveen
 
Ranch Hand
Posts: 287
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I perfectly understand as ConcurrentModificationException is thrown when a thread iterating over it AND modifying it.



using enhanced for loop...you are iterating through the collection and by calling poll(), you are modifying it. And yes priority queue is a collection
 
Saloon Keeper
Posts: 14853
334
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Harsha is correct. The enhanced for loop can only be used on arrays and subtypes of Iterable. The enhanced for loop will use the iterator to iterate through all the elements, so it's always a bad idea to remove elements from a collection using an enhanced for loop. Instead, you should use the normal for-loop, with the iterator:
 
naveen yadav
Ranch Hand
Posts: 384
MyEclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i mistaken foreach() loop as a normal for() loop. .
Thanks for clearing this.



Regards
naveen
 
Something must be done about this. Let's start by reading this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic