Saturday, May 01, 2010

Memory Intensive Operation In Java

Memory intensive processing without bloating Java Heap ????

Not many must be aware of the package java.lang.ref.*, and their impact on Garbage Collectors,
  1. Strong Reference (Frequently used)
  2. Soft Reference
  3. Weak Reference
A sample to demonstrate the references here, this program will fail with OutOfMemory without a weak reference (as we all know). With weak reference you can see the program runs for ever.

But the downside is the GC will treat these references low in priority and does cleans it up from the heap, you are bound to see Null Pointer Exceptions. Another alternate is SoftReferences which could fit in very well in most of the business cases and keep your memory foot print clean.

public class WeakRef {
public static WeakReference lst = new WeakReference(new ArrayList());
public static void main(String[] args) {
while (true) {
try {
lst.get().add("EEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Leaving this article a WeakReference to StrongReferences below,
  1. http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
  2. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/package-summary.html


No comments: