Problems with ServiceLoader dual iterator

Is this a known issue? I could not find the search results.

When an iteration over the ServiceLoader is already in progress during the iteration, the first iteration will be aborted. For example, if it is assumed that there are at least two implementations of Foo , the following code will fail with AssertionError:

 ServiceLoader<Foo> loader = ServiceLoader.load(Foo.class); Iterator<Foo> iter1 = loader.iterator(); iter1.next(); Iterator<Foo> iter2 = loader.iterator(); while (iter2.hasNext()) { iter2.next(); } assert iter1.hasNext(); 

This seems to happen if the second iterator actually completes. Code will succeed in this option, for example:

 ServiceLoader<Foo> loader = ServiceLoader.load(Foo.class); Iterator<Foo> iter1 = loader.iterator(); iter1.next(); Iterator<Foo> iter2 = loader.iterator(); iter2.next(); assert iter1.hasNext(); 

Is this a bug or a function ?: P

Is there a ticket for this anywhere else?

+4
source share
1 answer

It could be a mistake. I think this is because iterator.next () calls next () on the same lazy iterator link inside. This behavior violates the Least Surprise Principle.

+2
source

Source: https://habr.com/ru/post/1306260/


All Articles