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 {
} catch (Exception e) {

Leaving this article a WeakReference to StrongReferences below,

No comments: