I am getting out of memory error with just 50000 objects.
I checked computeIfAbsent
implementation but unfortunately did not find any thing peculiar.
My machine configuration is 16 GB
ram and core I7
.
public class Test {
public static void main(String[] args) {
int count = 50000;
List<ListObject> list = new ArrayList();
for (int i = 0; i < count; i++) {
int key = ThreadLocalRandom.current().nextInt(100000);
int value = ThreadLocalRandom.current().nextInt(1000000);
list.add(new ListObject(key, value));
}
Map<Integer, List<Integer>> map = new HashMap();
for (ListObject a : list) {
map.computeIfAbsent(a.getKey(), ArrayList::new);
}
System.out.println("Done");
}
and my ListObject is below:
class ListObject {
public ListObject(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
private int key;
private int value;
}
Can some one please help me understand this behavior.
The erroneous part is this:
ArrayList::new
What you don't realise is that this is not inferred to
() -> new ArrayList<>()
but to
key -> new ArrayList<>(key)
i.e. every list is created with a random size from 0 to 100000. Worst case that's 5 billion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With