Java strong references, soft references, weak references, and virtual references

Source: Internet
Author: User

 

1. 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. Figure 1 shows the application class hierarchy of the object. Figure 1 (1) strongreference a strong reference is the most common reference. 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 will not recycle strongly referenced objects to solve the problem of insufficient memory. (2) soft reference (softreference) if an object has only soft reference, the garbage collector will not recycle the object if the memory space is insufficient. 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) The difference between weakreference and soft reference 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 once only weakly referenced objects are found, regardless of 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) Virtual Reference (phantomreference), as its name implies, is essentially a virtual reference. Unlike other types of references, virtual reference does 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 =NewReferencequeue (); phantomreference Pr =NewPhantomreference (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 judgmentIn 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 to which it is directed 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. The question is how to judge the accessibility of an object: ◆ accessibility of a single reference path: In this path, the weakest reference determines the accessibility of an object. ◆ 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 data3.1 why should I use soft references? First, let's look at an instance of the employee information query 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, the
The end reference of the Java object allows the garbage collection thread to recycle the memory space occupied by the object. When the user needs to browse the employee's file 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 softreference is used, one of its instances stores a soft reference to a Java object, the existence of this soft reference will not prevent the garbage collection thread from recycling 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 =NewMyobject (); softreference asoftref =NewSoftreference (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 a soft reference object as a Java object. softreference objects not only have the special nature 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 softreference object is created
The referencequeue object is the constructor provided to softreference as a parameter, for example:
Referencequeue queue =NewReferencequeue (); softreference ref =NewSoftreference (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, then it will return the one before the queue
Reference object. 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 by using soft and object re-retrieval methods. The features of the garbage collection mechanism on the Java2 Platform and the aforementioned method for garbage object re-retrieval are used, 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 classEmployee {PrivateString ID; // employee IDPrivateString name; // employee namePrivateString Department; // department of the employeePrivateString phone; // contact number of the employeePrivate intSalary; // salary of the employeePrivateString origin; // the source of the employee information // ConstructorPublicEmployee (string ID ){This. ID = ID; getdatafromlnfocenter () ;}// obtain employee information from the databasePrivate voidGetdatafromlnfocenter () {// establish a connection well with the database to query the information of the employee and assign the query result to name, department, plone, salary and other variables // assign the origin value to "from database "}......
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: ImportJava. Lang. Ref. referencequeue; ImportJava. Lang. Ref. softreference; ImportJava. util. hashtable; Public classEmployeecache { Static privateEmployeecache Cache; // A cache instance PrivateHashtable <string, employeeref> employeerefs; // used for chche content storage PrivateReferencequeue <employee> q; // The spam reference queue // inherits softreference, so that each instance has a recognizable identifier. // And the ID is the same as the key in the hashmap. Private classEmployeeref ExtendsSoftreference <employee> { PrivateString _ key = ""; PublicEmployeeref (employee em, referencequeue <employee> q ){ Super(EM, q); _ key = em. GETID () ;}// build a cache instance PrivateEmployeecache () {employeerefs = NewHashtable <string, employeeref> (); q = NewReferencequeue <employee> ();} // retrieves a cache instance Public staticEmployeecache getinstance (){ If( Cache= Null){ Cache= NewEmployeecache ();} Return Cache;} // Reference the instance of an employee object in soft reference mode and save the reference Private voidCacheemployee (employee em) {cleancache (); // clear spam reference employeeref ref = NewEmployeeref (EM, q); employeerefs. Put (Em. GETID (), ref);} // obtain the instance of the corresponding employee object based on the specified ID. PublicEmployee getemployee (string ID) {employee em = Null; // Whether the soft reference of the employee instance exists in the cache. If yes, it is obtained from the soft reference. 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, // and save the soft reference to the new instance If(Em = Null) {Em = NewEmployee (ID); system. Out. Println ("retrieve from employeeinfocenter. ID =" + id ); This. Cacheemployee (EM );} ReturnEm;} // clear the employeeref objects that have been recycled by the soft referenced employee object Private voidCleancache () {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: 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.