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.
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.
Keeps objects alive provided there’s enough memory.
SoftReference can be used as a memory-sensitive cache, but it can exacerbate low memory conditions.
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.
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
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.
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.
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
- When you iterate through it, you get the pairs in insertion order, or in least-recently-used (LRU) order.
- 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).
- A thread-safe Map which does not involve synchronization locking.
- A hash map that uses == instead of equals( ) to compare keys. Only for solving special types of problems; not for general use.
Post a Comment


Java (159) Lucene-Solr (110) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Troubleshooting (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Problem Solving (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) Lesson Learned (5) Programmer Skills (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) System Design (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts