Java strong reference, soft reference, weak reference, Virtual Reference, java reference

Source: Internet
Author: User
Tags java reference

Java strong reference, soft reference, weak reference, Virtual Reference, java reference
Zookeeper1. Strong, soft, weak, and virtual references of ObjectsIn versions earlier than JDK 1.2, if an object is not referenced by any variable, the program will no longer be able to use this object. That is, the program can use an object only when it is in a reachable state. In JDK 1.2, object reference is divided into four levels, so that the program can control the object lifecycle more flexibly. The four levels are from high to low: strong reference, soft reference, weak reference, and virtual reference. It is an object application class level.
(1) StrongReference)
Strong references are the most common references. If an object has a strong reference, the garbage collector will never recycle it. When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally, and does not recycle strongly referenced objects at will to solve the problem of insufficient memory. (2) SoftReference)If an object only has soft references, the memory space is sufficient and the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache (as shown in the following example ).Soft references can be used together with a ReferenceQueue. If the referenced objects are recycled by the garbage collector, the Java virtual machine adds this soft reference to the reference queue associated with it. (3) WeakReference)The difference between weak references and soft references is that only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references.Weak references can be used together with a ReferenceQueue, the Java virtual machine adds this weak reference to the reference queue associated with it. (4) PhantomReference)As the name implies, "virtual references" are just the same as virtual ones, which are different from other types of references. Virtual references do not determine the object lifecycle. If an object only holds a virtual reference, it is the same as no reference and may be recycled by the garbage collector at any time.Virtual references are used to track the activity of objects recycled by the garbage collector. A difference between virtual and soft references and weak references is that virtual references must be used together with the reference Queue (ReferenceQueue. When the garbage collector is preparing to recycle an object, if it finds that it has a virtual reference, it will add this virtual reference to the reference queue associated with it before it recycles the object's memory.

ReferenceQueue queue = new ReferenceQueue ();PhantomReference pr = new PhantomReference (object, queue );
The program can determine whether the referenced object has been added to the reference queue to check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take necessary action before the memory of the referenced object is recycled.
2. Object accessibility judgment
In many cases, an object is not directly referenced from the root set, but is referenced by other objects or even several objects at the same time, to form a tree structure with the root set as the top. 2.
In this tree-like reference chain, the direction of the arrow represents the direction of reference, and the object is the referenced object. The figure shows that there are many paths from the root set to an object. For example, there are two paths (1-5 and 3-7) that reach object 5. This raises the question of how to judge the accessibility of an object: ◆ Single reference path accessibility judgment: In this path, the weakest reference determines the accessibility of objects. ◆ Determination of accessibility of multiple reference paths: the most powerful reference in several paths determines the accessibility of objects. For example, assume that the references ① and ③ In Figure 2 are strong references, ⑤ is soft references, and 7 is weak references. For object 5, follow these two judgment principles, path ①-⑤ takes the weakest reference ⑤, so the reference of this path to object 5 is soft reference. Similarly, ③-7indicates a weak reference. Take the strongest reference between the two paths, so object 5 is a soft object.
3. Use soft references to build a cache for sensitive data 3.1 why should I use soft references? First, let's look at an instance of employee information inquiry system. We will use a Java-based employee information query system to query information about Employee personnel files stored in disk files or databases. As a user, we may need to go back and view the employee profile information several minutes or even several seconds ago (similarly, we often use the "back" button when Browsing Web pages ). At this time, we usually have two program implementation methods: one is to save the previously viewed employee information in the memory, the life cycle of every Java object that stores employee profile information throughout the application; the other is when the user starts to view the profile information of other employees, end the reference of the Java object that stores the employee profile information previously viewed, so that the garbage collection thread can recycle the memory space occupied by it, when the user needs to browse the employee's profile information again, the information of the employee is rebuilt. Obviously, the first implementation method will cause a large amount of memory waste, and the second implementation is flawed even if the garbage collection thread has not collected garbage, objects that contain employee profile information are still stored in the memory in good condition, and applications need to recreate an object. We know that accessing disk files, accessing network resources, and querying databases are all important factors that affect application execution performance. If you can obtain references of Java objects that have not been recycled, unnecessary access will be reduced, greatly improving the program running speed.   3.2 If soft reference is used
SoftReference is characterized by a soft reference of a Java object saved by an instance. The existence of this soft reference does not prevent the garbage collection thread from reclaiming the Java object. That is to say, once SoftReference saves a soft reference to a Java object, the get () provided by the SoftReference class before the garbage thread recycles this Java object () method returns a strong reference to a Java object. In addition, once the garbage thread recycles the Java object, the get () method returns null. See the following code:
MyObject aRef = new MyObject ();SoftReference aSoftRef = new SoftReference (aRef );
In this case, there are two reference paths for this MyObject object, one is soft reference from the SoftReference object and the other is strong reference from the aReference variable. Therefore, this MyObject object is strongly accessible. Then, we can end the strong reference of aReference to this MyObject instance:
ARef = null;
Since then, this MyObject object has become a soft object. If the garbage collection thread collects garbage in memory, it does not always keep the object because SoftReference references the object. Java Virtual Machine garbage collection threads Treat Soft and object and other general Java objects differently: soft and object cleanup is determined by the garbage collection thread according to its specific algorithm according to memory requirements. That is to say, the garbage collection thread recycles soft and objects before the Virtual Machine throws an OutOfMemoryError. In addition, the virtual opportunity tries its best to recycle soft and objects that are idle for a long time, virtual machines will try to retain the "new" soft object that has just been built or used. Before recycling these objects, we can use:
MyObject anotherRef = (MyObject) aSoftRef. get ();
Obtain a strong reference to the instance again. After recycling, you can only get null by calling the get () method.   3.3 Use ReferenceQueue to clear SoftReference that has lost soft reference objects
As a Java object, SoftReference objects not only have the special characteristics of Saving Soft references, but also have the general nature of Java objects. Therefore, after soft availability and object collection, although the get () method of the SoftReference object returns null, The SoftReference object no longer has value, an appropriate clearing mechanism is required to avoid Memory leakage caused by a large number of SoftReference objects. ReferenceQueue is also provided in the java. lang. ref package. If a ReferenceQueue object is used as a parameter when a SoftReference object is created, the constructor is provided to SoftReference, for example:
ReferenceQueue queue = new ReferenceQueue ();SoftReference ref = new SoftReference (aMyObject, queue );
When the soft reference aMyOhject of SoftReference is recycled by the garbage collector, the SoftReference object strongly referenced by ref is included in ReferenceQueue. That is to say, the object stored in ReferenceQueue is a Reference object, and it is a Reference object that has lost its soft Reference. In addition, we can see from the ReferenceQueue name that it is a queue. When we call its poll () method, if this queue is not a blank queue, the Reference object before the queue is returned. At any time, we can call the poll () method of the ReferenceQueue to check whether there are any non-strong and the objects it cares about are recycled. If the queue is empty, a null value is returned. Otherwise, the method returns a Reference object before the queue. With this method, we can check which SoftReference soft referenced object has been recycled. So we can clear the SoftReference objects that have lost the soft referenced objects. Common Methods:
SoftReference ref = null;While (ref = (EmployeeRef) q. poll ())! = Null ){// Clear ref}
After understanding the ReferenceQueue's working mechanism, we can start to construct a Java object high-speed cache.   3.4 implement high-speed cache of Java objects through soft and object re-retrieval methods Using the features of the garbage collection mechanism on the Java2 Platform and the aforementioned garbage object re-acquisition method, we use a small example of an employee information query system to illustrate how to build a high-speed cache to avoid performance loss caused by repeated construction of the same object. We define an Employee's profile information as an Employee class:
Public class Employee {Private String id; // employee idPrivate String name; // employee namePrivate String department; // department of the employeePrivate String Phone; // contact number of the employeePrivate int salary; // salary of the employeePrivate String origin; // The Source of employee information // ConstructorPublic Employee (String id ){This. id = id;GetDataFromlnfoCenter ();} // Obtain employee information from the databasePrivate void getDataFromlnfoCenter (){// Establish a connection well with the database to query the employee's information and assign the query result a value// Give variables such as name, department, plone, and salary// Assign the origin value to "From DataBase" at the same time"}......
In the constructor of this Employee class, we can foresee that if you need to query the information of an Employee every time. It takes a lot of time to build a new instance, even if it was just queried in a few seconds. The following is a definition of the cache for caching the Employee object:
Import java. lang. ref. ReferenceQueue;Import java. lang. ref. SoftReference;Import java. util. Hashtable;Public class EmployeeCache {Static private EmployeeCacheCache; // A Cache instancePrivate Hashtable <String, EmployeeRef> employeeRefs; // used for Chche content storagePrivate ReferenceQueue <Employee> q; // spam Reference queue // Inherit SoftReference so that every instance has a recognizable identifier.// And the ID is the same as the key in the HashMap.Private class EmployeeRef extends SoftReference <Employee> {Private String _ key = ""; Public EmployeeRef (Employee em, ReferenceQueue <Employee> q ){Super (em, q );_ Key = em. getID ();}} // Construct a cache instancePrivate EmployeeCache (){EmployeeRefs = new Hashtable <String, EmployeeRef> ();Q = new ReferenceQueue <Employee> ();} // Obtain the cache instancePublic static EmployeeCache getInstance (){If (Cache= Null ){Cache= New EmployeeCache ();}ReturnCache;} // Reference the instance of an Employee object in soft reference mode and save the referencePrivate void cacheEmployee (Employee em ){CleanCache (); // clear spam referenceEmployeeRef ref = new EmployeeRef (em, q );EmployeeRefs. put (em. getID (), ref );} // Obtain the instance of the corresponding Employee object based on the specified ID number.Public Employee getEmployee (String ID ){Employee em = null;// Check whether soft references of the Employee instance exist in the cache. If so, obtain them from soft references.If (employeeRefs. containsKey (ID )){EmployeeRef ref = (EmployeeRef) employeeRefs. get (ID );Em = (Employee) ref. get ();}// If there is no soft reference, or the Instance obtained from the soft reference is null, re-build an instance,// Save the soft reference for the new instanceIf (em = null ){Em = new Employee (ID );System.Out. Println ("Retrieve From EmployeeInfoCenter. ID =" + ID );This. cacheEmployee (em );}Return em;} // Clear the EmployeeRef objects that have been recycled by the soft referenced Employee objectPrivate void cleanCache (){EmployeeRef ref = null;While (ref = (EmployeeRef) q. poll ())! = Null ){EmployeeRefs. remove (ref. _ key );}}

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: 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.