1

There will be a OOM error in creating so many Strong Reference is because of GC won't collect Strong Reference, but GC will collect Weak Reference if there no extra memory. So my question is : I create a loop to create Weak Reference while I set my -Xmx2M

Set<SoftReference<Integer>> sa = new HashSet<~>();
for (int i = 0; i < size; i++) {
     SoftReference<Integer> ref = new SoftReference<Integer>(i);
     sa.add(ref);
}

It's still occur OOM, Why?

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
solomons
  • 39
  • 3

1 Answers1

7

It's still occur OOM, Why?

The Integers are being cleaned up however the HashSet and the SoftReferences don't get removed by the GC. Note: A SoftReference object is larger than an Integer object.

What you can do is the follow to never run out of memory.

SoftReference<HashSet<Integer>>> sa = null;
for (int i = 0; i < size; i++) {
    if (sa == null || sa.get() == null)
        sa = new SoftReference<HashSet<Integer>>(new HashSet<Integer>());
    sa.get().add(ref);
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130