Understanding Java References


J2SE Knowledge Series - Part 2

Understanding Java References

There are four types of references in java, strong reference,
SoftReference, WeakReference and PhantomReference.
If an object has strong reference, garbage collector will never reclaim its storage.
The latter three reference types provide access to an object but without preventing it from being freed.
It provides a limited degree of interaction with the garbage collector.
SoftReference
The idea of a SoftReference is that your soft references will only be cleared, when system memory is low.
The garbage collector can arbitrarily free an object whose only reference is a soft reference.
This depends on the algorithm of the garbage collector as well as the amount of memory available while the collector is running.
The garbage collector is required to release any soft references before throwing an OutOfMemoryException.
Features
Keeps objects alive provided there’s enough memory.
Usage
SoftReference can be used as a memory-sensitive cache, but it can exacerbate low memory conditions.
WeakReference
Weak references are weaker than soft references. If the only references to an object are weak references, the garbage collector can reclaim the memory used by an object at any time(usually on the next collection). There is no requirement for a low memory situation.
Features
Compared with SoftReference, WeakReference will be GC-d by the JVM eagerly.
The weak references would be cleared as soon as no strong or soft refs remain, but usually it may take multiple runs of the garbage collector before it finds and frees a weakly reachable object.
Cleared ASAP, before the finalizer runs.
Not for caching! Use soft references, as intended
Usage
WeakReference are usually used to automatically reclaim resource when last stronger/soft reference is gone.
Most of the WeakReferences use cases needs a Map data structure, so JDK provides WeakHashMap for us to use.
WeakReference is used internally by the WeakHashMap class.
We may forget to unregister a listener when it is no longer used or some, or it may be difficult to determine when to unregister it, this may cause memory leak.
As an option, we can use weak listener to make it automatically unregistered when no strong/soft reference to it.
PhantomReference
A phantom reference is quite different than either SoftReference or WeakReference.
Phantom Reference isn't meant to be used to access the object, but as a signal that the object has already been finalized, and the garbage collector is ready to reclaim its memory.
The PhantomReference class is useful only to track the impending collection of the referring object. As such, it can be used to perform pre-mortem cleanup operations. A PhantomReference must be used with the ReferenceQueue class.
The ReferenceQueue is required because it serves as the mechanism of notification. When the garbage collector determines an object is phantomly reachable, the PhantomReference object is placed on its ReferenceQueue.
Calling get() on a PhantomReference always returns null, so you must use it with a reference queue.
A PhantomReference is enqueued after finalization of the object. A WeakReference is enqueued before.
Usage
PhantomReferences can be used to determine exactly when an object is about to be removed from memory
Phantom references relate to pre-mortem cleanup tasks.
PhantomReferences can be used as a replacement of finalize() method. - Lets you clean up after finalization but before the space is reclaimed.
Problem with Finalization
Finalization is unpredictable and nondeterministic process - They're not guaranteed to run, especially not timely.
Finalizations can slowdown an application.
   - They can make allocation/reclamation 430X slower!(Effective Java)
   - Finalizers have an impact on the performance of the garbage collector since Objects with finalizers are slow to garbage collect, especially when the finalize method may run for a long time.
Undefined threading model; they can run concurrently, this can cause potential problems.
Exceptions thrown are ignored (per spec).
You should only use finalization only when it is absolutely necessary.
It can be used as a safety measure, but not necessary.
WeakHashMap associates key objects with values, it keeps weak refs to keys, strong refs to values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed.
It is a storage-saving technique, WeakHashMap allows the garbage collector to automatically clean up the keys and values when there are no strong/soft reference to the keys outside the map.
WeakHashMap wraps the key as a WeakReference automatically.
HashMap is intended to replace Hashtable.
Map types
HashMap
LinkedHashMap
- When you iterate through it, you get the pairs in insertion order, or in least-recently-used (LRU) order.
TreeMap
- Implementation based on a red-black tree. When you view the keys or the pairs, they will be in sorted order (determined by Comparable or Comparator).
WeakHashMap
ConcurrentHashMap
- A thread-safe Map which does not involve synchronization locking.
IdentityHashMap
- A hash map that uses == instead of equals( ) to compare keys. Only for solving special types of problems; not for general use.
Resources

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)