Java reference types and common applications

Source: Internet
Author: User

The type of reference is primarily concerned with how the reference interacts with the GC.

1.Strong References
Common reference types in Java:

StringBuffer buf = new StringBuffer();

Here buf is a strong reference. If an object is up to a strong reference chain, it is not suitable for GC and will not be recycled.

2.Weak References
A weak reference, which is a weaker reference, does not prevent the GC from reclaiming objects that are referenced only by weak references.
When an object is strongest and only referenced by a weak reference, it can be recycled in the next GC cycle.
You can build a weak reference using the following method:

WeakReference<Widget> weakWidget = new WeakReference<Widget>(widget);

Elsewhere you can use the following code to get the original object:

weakWidget.get()

But you might get a null value.
Common classes that use to weak references are:
Threadlocal class:

Java.util.WeakHashMap

3.Soft References
Soft references, like weak references, are recycled in the next GC cycle, but soft references generally persist longer.
More commonly, soft references, as long as the memory is sufficient, will persist.
Then it's a great fit for caching.
is an inheritance graph in the JDK and can see a lot of cache-related.

More information can be found in Google Guava:
Com.google.common.collect.MapMakerInternalMap

4.Phantom References
The Phantom Reference, a weaker reference, the weakest, and its get () method always returns NULL.
It is typically used to get a notification when the object GC is notified that you can do something else,
This class is used skillfully in Apache's commons-fileupload and Commons-io to enable the removal of temporary files when uploading.
In Commons-fileupload, each file specifies a file-cleared tracker.

org.apache.commons.fileupload.disk.DiskFileItemFactory.fileCleaningTracker

And Commons-io, the most important in: The Reaper thread of the Run method. (Part of the code is removed.)

 PackageOrg.apache.commons.io;/** * keeps track of files awaiting deletion, and deletes them when a associated * marker object is reclaimed by the Garbage collector. * <p> * This utility creates a background thread to handle file deletion. * Each file to being deleted is registered with a handler object. * When the handler object was garbage collected, the file is deleted. * <p> * Environment with multiple class loaders (a Servlets container, for * example), you should consider stop Ping the background thread if it is no * longer needed. This is do by invoking the method */Public class filecleaningtracker {    //Note:fields is package protected to, use by test cases    /** * Queue of <code>Tracker</code> instances being watched. */referencequeue<object> q =NewReferencequeue<object> ();/** * Collection of <code>Tracker</code> instances in existence. */    FinalCollection<tracker> trackers = Collections.synchronizedset (NewHashset<tracker> ());//Synchronized    /** * Whether to terminate the thread when the tracking are complete. */Volatile Boolean exitwhenfinished =false;/** * The thread that'll clean up registered files. */Thread Reaper;/** * The specified file, using the provided marker, deleting the file * When the marker instance is GAR     Bage collected.     * The speified deletion strategy is used. * * @param path The full path to the file to is tracked, NOT NULL * @param marker the marker o Bject used to track the file, NOT NULL * @param deletestrategy The strategy to delete the file, null means n Ormal * @throws NullPointerException If the path is null * /public void Track (FinalString Path,FinalObject Marker,FinalFiledeletestrategy deletestrategy) {if(Path = =NULL) {Throw NewNullPointerException ("The path must not being null");    } addtracker (path, marker, deletestrategy); }/** * Adds a tracker to the list of trackers. * * @param path The full path to the file to is tracked, NOT NULL * @param marker the marker o Bject used to track the file, NOT NULL * @param deletestrategy The strategy to delete the file, null means n Ormal * *    Privatesynchronized void Addtracker (FinalString Path,FinalObject Marker,FinalFiledeletestrategy deletestrategy) {//Synchronized block protects Reaper        if(exitwhenfinished) {Throw NewIllegalStateException ("No new trackers can added once exitwhenfinished () is called"); }if(Reaper = =NULL) {Reaper =NewReaper ();        Reaper.start (); } trackers.add (NewTracker (path, deletestrategy, marker, q)); }//-----------------------------------------------------------------------    /** * The Reaper thread. */    Private Final  class Reaper extends Thread {        /** Construct A new Reaper * /Reaper () {Super("File Reaper");            SetPriority (thread.max_priority); Setdaemon (true); }/** * Run The Reaper thread that would delete files as their associated * marker objects is reclaimed         By the garbage collector. */        @Overridepublic void Run () {//thread exits when exitwhenfinished was true and there is no more tracked objects             while(exitwhenfinished = =false|| Trackers.size () >0) {Try{//Wait for a tracker to remove.                    FinalTracker Tracker = (Tracker) q.remove ();//cannot return nullTrackers.remove (tracker);if(!tracker.delete ())                    {Deletefailures.add (Tracker.getpath ());                } tracker.clear (); }Catch(FinalInterruptedexception e) {Continue; }            }        }    }//-----------------------------------------------------------------------    /** * Inner class which acts as the reference for a file pending deletion. */    PrivateStaticFinal  class Tracker extends phantomreference<Object> {        /** * The full path to the file being tracked. */        Private FinalString path;/** * The strategy for deleting files. */        Private FinalFiledeletestrategy Deletestrategy;/** * Constructs an instance of this class from the supplied parameters. * * @param path The full path to the file to is tracked, NOT NULL * @param deletestrate GY the strategy to delete the file, null means normal * @param marker The marker object used to track T He file, not NULL * @param queue the queue the which the tracker would be pushed, not null */
     Tracker (FinalString Path,FinalFiledeletestrategy Deletestrategy,FinalObject Marker,Finalreferencequeue<?SuperObject> queue) {Super(marker, queue); This. Path = path; This. Deletestrategy = Deletestrategy = =NULL?        FileDeleteStrategy.NORMAL:deleteStrategy; }/** * Deletes the file associated with this tracker instance.         * * @return {@code true} if the file was deleted successfully;         * {@code false} otherwise. */public Boolean Delete () {returndeletestrategy.deletequietly (NewFile (path)); }    }}

Java reference types and common applications

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.