Java supports four types of references(Strong, Soft, Weak and Phanthom). We have these reference types to control the memory allocation and de-allocation from our programs. Having only strong references and let the GC manage memory may be simple, but we wont have any control.
- Strong references:
Strong references are normal references to the objects which we use every day in our java programs. Objects with strong references are eligible for garbage collection only when we de-reference the objects. This is one of the potential candidate for memory leaks.
1 2 | |
- Soft reference
Garbage collector will collect the soft reference objects only when it needs to (e.g. when its reaching memory limit). All soft references will be reclaimed before an OutofMemory exception is thrown. Soft references are mainly used for caching purpose, say you want to cache large image files.
1 2 | |
Soft references are relatively stronger than weak reference (another type!). I would call it as lazy reference i.e. We ask GC to delay the garbage collection till the end or necessary.
Weak reference
Weak references are references to the objects which are not gaurenteed to exist when we try to access the object. Garbage collector (GC) will eagerly kill the weakly referenced objects.Weak references are Garbage collected even though the memory is abundant. References are cleared before finalizer runs. this.weakref = new java.lang.ref.WeakReference(obj);
Phanthom reference
Phantom reference points to an object which is already dead. This is the least strong referenes of all. Only use of Phanthom reference is to cleanup after finalisation but before reclaiming the memory.If an object cannot be reached by any of the above four reference types then its eligible for garbage collection.
References:
Understanding weak reference
Why do we need weak reference
Phanthon refernce