Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted out of memory error in ArrayList::new - Why? [duplicate]

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.

like image 552
Sachin Sachdeva Avatar asked Dec 09 '19 09:12

Sachin Sachdeva


1 Answers

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.

like image 64
2 revs Avatar answered Oct 30 '22 20:10

2 revs