Reputation: 2696
When creating large lists I ran into something odd. I created sub lists, because the entire list was too large. But when checking the resulting sizes I found:
new ArrayList<>(rSet).size() != rSet.size();
Where rSet is a HashSet
When I stop eclipse and investigate, I see that rSet has 1000 items, whilst responding to .size() as having less (the number of less
items fluctuates; sometimes the rSet.size()
is higher than the values it actually contains). I cannot reproduce this in a separate test case; the code has too many layer to provide. But is filled from separate threads, which are ended by the time size
is called.
I said I filled it from threads. I provide the Set<> rSet
as parameter to all threads, and use the following method to add new items to the set:
public static void addSynchronized(final Set<?> c, final List<?> items) {
c.addAll(items);
}
I must be doing something the code disagrees with... But what?
Upvotes: 0
Views: 223
Reputation: 181815
is filled from separate threads
I think there's your problem. HashSet
is not thread-safe. When writing to it from multiple threads at the same time, anything could happen.
To make it synchronized (from the docs):
Set s = Collections.synchronizedSet(new HashSet(...));
Your addSynchronized
method has a misleading name, because it's not synchronized
. (Having an argument named list
that's actually a Set
is a bit confusing as well.)
Upvotes: 2