ConcurrentModificationException in java.util.ServiceLoader (not a multi-thread issue)

David Holmes david.holmes at oracle.com
Tue Feb 24 01:32:03 UTC 2015


On 24/02/2015 12:20 AM, Martin Desruisseaux wrote:
> Hello all
>
> java.util.ServiceLoader does not seem to support usage of a second
> Iterator in the middle of a previous iteration.

Nope it doesn't. At a minimum this should be documented. The distinct 
Iterator instances returned by iterator() share the same lazy-lookup 
iterator.

David
-----

  The attached Java file
> provides two simple tests with a ServiceLoader iterating over two
> elements. The first test creates two iterators and invokes their
> hasNext() / next() methods in the following order:
>
>    * Iterator 1
>    * Iterator 2
>    * Iterator 1
>    * Iterator 2  -  unexpected end of iteration here.
>
> The second test creates two iterators and invoke the hasNext() methods
> on both iterators before to invoke their next() methods. This result is
> the following exception (tested on 1.8.0_31-b13):
>
>      Exception in thread "main" java.util.ConcurrentModificationException
>      	at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:711)
>      	at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:744)
>      	at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:742)
>      	at java.util.ServiceLoader$1.next(ServiceLoader.java:479)
>      	at test.ServiceLoaderTest.test2(ServiceLoaderTest.java:47)
>      	at test.ServiceLoaderTest.main(ServiceLoaderTest.java:12)
>
> (note: to run the test, the attached test.ServiceLoaderTest file needs
> to be in the META-INF/services/ directory). I found a Stackoverflow
> thread mentioning this issue 4 years ago [1], but apparently without
> solution. Should I look for a patch, or is the current behaviour
> considered okay (in which case I would suggest to warn the users in the
> Javadoc)?
>
>
>      Martin
>
>
> [1] http://stackoverflow.com/questions/2593777/serviceloader-double-iterator-issues
>
>



More information about the core-libs-dev mailing list