Java Reference Types

Source: Internet
Author: User

References

Java provides different types/classes of Reference Objects:strong and weak. Weak Reference Objects can is further divided into soft and phantom.

Strong Reference

StringBuilder builder = new StringBuilder(); 

This is the default Type/class of Reference object, and if not differently specified: is builder a strong Reference object. This kind of reference makes the referenced object isn't eligible for GC. That was, whenever an object was referenced by a chain of strong Reference Objects, it cannot was garbage collected.

Weak Reference

WeakReference<StringBuilder> weakBuilder = new WeakReference<StringBuilder>(builder);

Weak Reference Objects is not the default type/class of Reference Object and to being used they should be explicitly specifi Ed like in the above example. This kind of reference makes the Reference object eligible for GC. That's, in case the only reference reachable for the StringBuilder object in memory are, actually, the weak reference, the n the GC is allowed to garbage collect the StringBuilder object. When a object in memory was reachable only by Weak Reference Objects, it becomes automatically eligible for GC.

Soft Reference

Garbage collector can collect an object if only weak references is pointing towards it and they is eagerly collected, on The other hand Objects with SoftReference is collected when the JVM absolutely needs memory.

Phantom Reference

Object which only have Phantom reference pointing them can be collected whenever garbage Collector likes it.

Useful Classes

Weakhashmap

Hash table based implementation of the Map interface, with weak keys. An entry in a Weakhashmap would automatically be removed when it key is no longer on ordinary use. More precisely, the presence of a mapping for a given key would not be prevent the key from being discarded by the garbage col Lector, that's, made finalizable, finalized, and then reclaimed. When a key have been discarded its entry are effectively removed from the map, so this class behaves somewhat differently fr Om other Map implementations.

Referencequeue

If The garbage collector discovers an object it is weakly reachable, the following occurs:

    • The WeakReference object ' s referent field is set to NULL, thereby making it isn't refer to the heap object any longer.
    • The heap object that had been referenced by the WeakReference is declared finalizable.
    • The WeakReference object is added to its referencequeue. Then the heap object's Finalize () method is run and its memory freed.

When creating Non-strong reference objects we had the option of passing a reference queue as a part of the reference cons Tructor. As seen from the above explanation, this reference queue is a-to-the-the-GC to-Inform the program, a certain object I s no longer reachable.

Example
ImportJava.lang.ref.ReferenceQueue;Importjava.lang.ref.WeakReference; Public classTest { Public Static voidMain (string[] args)throwsinterruptedexception {savepoint savepoint=NewSavePoint ("Random");//a Strong ObjectReferencequeue<SavePoint> SAVEPOINTQ =NewReferencequeue<savepoint> ();//The referencequeueWeakreference<savepoint> savepointwrefernce =NewWeakreference<savepoint>(SavePoint, SAVEPOINTQ); System.out.println ("SavePoint created as a weak ref" +savepointwrefernce);         Runtime.getruntime (). GC (); System.out.println ("Any weak references in Q?" + (Savepointq.poll ()! =NULL)); SavePoint=NULL;//The only strong reference have been removed. The heap//Object is now only weakly reachableSystem.out.println ("Now-to-call GC ..."); Runtime.getruntime (). GC (); //The object would be cleared Here-finalize would be called.System.out.println ("Any weak references in Q?" + (Savepointq.remove ()! =NULL)); System.out.println ("Does the weak reference still hold the heap object?" + (Savepointwrefernce.get ()! =NULL)); System.out.println ("Is the weak reference added to the referenceq?" +(savepointwrefernce.isenqueued ())); }}classSavePoint { Publicsavepoint (String value) {}}

The program:

  1. Creates a strong reference and adds it to a Weak reference savepointwrefernce. The object in memory are now referenced by a strong reference and a weak reference-hence strongly reachable.
  2. The first call to garbage collector won't clear our SavePoint object as it is a strong reference. Hence The poll method of the REFERENCEQ would return null. (Poll method is non-blocking it checks and returns immediately.)
  3. The savepoint reference variable is set to NULL. Our heap object was now referenced only by the weak reference-hence it is weakly reachable.
  4. The second GC call would now locate the object, executes its Finalize method and mark this object to be freed. Theobject is also added to the referenceq.
  5. A call to the Remove method of the REFERENCEQ would return the object. Remove is a blocking method. It'll wait till an object have been made available in the Queue. (Poll method might not work as the recycling process was happening on a separate thread.)

As seen once the object was a ready-to-be released it is added to the reference queue. So the reference queue was like a callback to our Java program, telling us, a particular object was released from its re Ference and is isn't available to our code anymore.

As seen from above the Reference queue actually holds within it's the weakreference which lost its heap object to clean up. The weakreference does not has any association to the memory object. The get call above returns NULL. Unlike with finalize when we can make the object alive again, and the referenceq there is no-to-reach the release D Java object. Reference Queues is just for References this got freed by garbage collection. They cannot is used to make alive our objects again. They can only is used to notify we code about the loss of memory objects referred to by these non-strong references.

Java Reference Types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.