Strong, soft, weak, and virtual references of Objects

Source: Internet
Author: User

This section describes the concepts, applications, and representations of strong, soft, weak, and virtual references of objects in UML.
1. Strong, soft, weak, and virtual references of Objects

In 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)

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 How to Use soft references

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 ID
Private string name; // employee name
Private string Department; // department of the employee
Private string phone; // contact number of the employee
Private int salary; // salary of the employee
Private string origin; // The Source of employee information
// Constructor
Public Employee (string ID ){

This. ID = ID;

Getdatafromlnfocenter ();

}
// Obtain employee information from the database
Private 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 employeecache cache; // a cache instance
Private hashtable <string, employeeref> employeerefs; // used for chche content storage
Private referencequeue <employee> q; // spam reference queue
// Inherit softreference so that every instance has a recognizable identifier.
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 instance
Private employeecache (){
Employeerefs = new hashtable <string, employeeref> ();
Q = new referencequeue <employee> ();
}
// Obtain the cache instance
Public static employeecache getinstance (){
If (Cache = NULL ){
Cache = new employeecache ();
}
Return cache;
}
// Reference the instance of an employee object in soft reference mode and save the reference
Private void cacheemployee (employee em ){
Cleancache (); // clear spam reference
Employeeref 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 instance
If (Em = NULL ){
Em = new employee (ID );
System. Out. println ("retrieve from employeeinfocenter. ID =" + id );
This. cacheemployee (EM );
}
Return em;
}
Private void cleancache (){
Employeeref ref = NULL;
While (ref = (employeeref) Q. Poll ())! = NULL ){
Employeerefs. Remove (ref. _ key );
}
}
// Clear all content in the cache
Public void upload AchE (){
Cleancache ();
Employeerefs. Clear ();
System. GC ();
System. runfinalization ();
}
}


Note: The original referencequeue only serves as a listener. When softreference is found. when the get () method returns a null value, softreference is registered to its own queue. When we call the poll () method of referencequeue, softreference is returned and deleted.

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.