DaveAKing / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Iterables.toArray broken in case of concurrent modifications #1558

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
In case the iterable shrinks in the meantime, the result of the class-accepting 
version of `Iterables.toArray` may contain nulls at its end.

The documentation says "return a newly-allocated array into which all the 
elements of the iterable have been copied", which actually doesn't prevent 
this. However, nobody expects `Iterables.toArray(a_not_null_allowing_set, 
some_class)` to contain several nulls.

In case you don't want to fix it, the documentation should state this very 
explicitly. Note that the other overload works fine.

The fix is trivial, just pass an empty array in place of the presized one. The 
only cost is the allocation of the empty array. A test is attached.

Original issue reported on code.google.com by Maaarti...@gmail.com on 19 Oct 2013 at 4:37

Attachments:

GoogleCodeExporter commented 9 years ago
Just to clarify: this breaks if Iterables.toArray is passed a *collection* 
which is modified concurrently?

Original comment by wasserman.louis on 19 Oct 2013 at 4:40

GoogleCodeExporter commented 9 years ago
Yes, in case of a non-collection it runs through 
`Lists.newArrayList(iterable.iterator())` which by taking a snapshot prevents 
the problem.

Albeit rather inefficient (everything gets copied into the ArrayList's array 
and then out again), it works fine in this case.

Original comment by Maaarti...@gmail.com on 19 Oct 2013 at 4:50

GoogleCodeExporter commented 9 years ago
My comment regarding the efficiency was wrong, as the ArrayList has typically a 
bigger  underlying array than size(), so copying is unavoidable.

Original comment by Maaarti...@gmail.com on 19 Oct 2013 at 6:58

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:12

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:17

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08