3 February 2009

Memory management in Java

Different look on memory leak problem.

We have garbage collector in Java, but this do not prevent us from make memory to leak. What more even standard library isn't leak-free.

How can we spare memory easly?

String.intern() is one of the easiest way.

  • It do not interfere with gc.
  • It's fast.
  • Multi thread safe.
I just need to check if .intern() work with .substring(...)

Where we loose memory quietly?

Most Classes created to store high amount of dynamic data have their own memory menage system. ArrayList, StringBuilder, ... they all allocate *2 memory. Which mean that is we have 1024 elements and need to add one while no free space is available then space will be extended to 2024.

How much memory do we loose?

Calling .trimToSize() can spare approximately 10% of memory.
On String.intern() I used to save up to 70%.

1 comment:

  1. Javassist, CGLIB, dynamic classloaders is the other source of memory that won't be garbage-collected (or will be garbage-collected infrequently).
    Unfortunately, Hibernate, Spring, JSF, Seam or EJB use them in large amounts. And then people wonder why a web application works in Java 10x slower than in PHP and eats 10x more memory.
    REFLECTION AND RUNTIME CODE GENERATION (=cglib) ARE EVIL. This extra code should be generated at compile time.