Skip to main content


Showing posts from June, 2012

Java: Strong References, Soft References and Weak References

There are many use-cases where we want to control, when our objects are collected by GC(Garbage Collector). Package "java.lang.ref" provides reference-object classes, which support a limited degree of interaction with the garbage collector. And GC reclaim the object memory based on it's reachability.

Strong Reference Newly created objects are strongly reachable by the thread that created it. So object will be remain in heap till thread is running or some variable hold this object reference.

//leaking array private static List<String> leakingArrayWithStrongRef = new LinkedList<String>(); public void StrongReferenceTest(){ try { for (int i = 0; i < 500000; i++) { String data = LEAKING_DATA + i; // Add data to our leaking array... leakingArrayWithStrongRef.add(data); } } catch (OutOfMemoryError ofm) { System.out.println(&quo…