default random access list spliterator

Tagir F. Valeev amaembo at gmail.com
Mon Mar 7 09:57:21 UTC 2016


Hello!

I thought about such possibility. One problem which would arise is
that such spliterator will not be able to properly track modCount and
throw ConcurrentModificationException. As a consequence it might
produce silently inconsistent result if the structural changes were
performed on your list during the traversal.

Note that currently you can override spliterator() in your List class
this way:

Spliterator<E> spliterator() {
  return IntStream.range(0,size()).mapToObj(this::get).spliterator();
}

Such one-liner produces a spliterator which splits nicely. The
drawback is that it's eager-binding and not fail-fast, so it's
definitely not an option for JDK, but possibly acceptable for your
project.

Another option for JDK would be to leave default List.spliterator()
implementation as is, but override it in AbstractList (which already
tracks modCount).

With best regards,
Tagir Valeev.

MH> The default List.spliterator() is iterator-based.  Could this be
MH> improved for random access lists, using List.get(int) to fetch
MH> elements instead of List.iterator()?

MH> I think it could improve most on Spliterator.trySplit().  The current
MH> implementation allocates a new array for split-off elements.  I see
MH> almost twice the throughput from list.parallelStream().forEach(...)
MH> with a custom get(int)-based implementation over the default one.

MH> For example, instead of this:

MH>     default Spliterator<E> spliterator() {
MH>         return Spliterators.spliterator(this, Spliterator.ORDERED);
MH>     }

MH> I'm suggesting something like this:

MH>     default Spliterator<E> spliterator() {
MH>         return (this instanceof RandomAccess)
MH>                 ? Spliterators.randomAccessListSpliterator(this)
MH>                 : Spliterators.spliterator(this, Spliterator.ORDERED);
MH>     }

MH> where randomAccessListSpliterator is new code that looks a lot like
MH> Spliterators.ArraySpliterator.

MH> -Michael




More information about the core-libs-dev mailing list