Four kinds java object reference: strong references, soft, weak, and references cited java virtual objects four references: strong references, soft, weak, and references cited imaginary

Four kinds java object reference: strong references, soft, weak, and references cited imaginary

Before JDK1.2, objects that are created only in the state is accessible (reachable), can be used by the program. In other words, if an object is not referenced by any variable, the program will no longer be able to use this object. Once these useless garbage collector found objects, it will be recycled. However, in some cases, we will want to have some objects need not be recovered immediately, or necessity from a global point of view there is no immediate recovery. Such as caching system design, not tight or in order to improve the operating efficiency of the case, not some temporary objects can still be placed in memory, rather than immediately recovered memory.

To meet this requirement, beginning from JDK1.2 version, Java's designers to reference objects subdivided into strong reference (Strong Reference), soft references (Soft Reference), weak references (Weak Reference) and virtual reference (Phantom Reference ) four levels, the guidelines are reflected in the breakdown of recycled GC priority: strong references> soft reference> weak reference> false references.

Thus, from the beginning of JDK1.2, GC garbage collector when the object is recovered, the validity of the analysis object not only need to consider the accessibility of the object, but also need to consider the reference to the object intensity, so that the program can be more flexible control of the object's life cycle. It can be summed up with a formula: the effectiveness of object reference type + = accessibility.

A strong reference (Strong Reference)

Strong reference represents an object in the [useful] must state, is the most commonly used reference. If an object has strong references, then the garbage collector will never recover it. Even in low memory situations, Java Virtual Machine would rather throw OutOfMemoryError error, the program terminates abnormally, it will not solve the problem of insufficient memory to recover the object through a strong reference.

Student student = new Student (); // This is a strong reference

Behind the soft, weak, and an imaginary reference object references cited it is based on a strong, strong reference to need. That means, the object must have a strong reference, then the strong fuss on the object referenced by the operation must turn it into a soft, weak, or imaginary objects referenced by reference.

Soft references (Soft Reference)

Soft reference represents an object in a [helpful, but not required] state. In memory space is sufficient, if an object has only soft references, then the garbage collector does not reclaim it, but if memory space is insufficient, the garbage collector will reclaim the object (recovery occurs before an OutOfMemoryError). As long as the garbage collector does not reclaim it, the object can be used by the program.

Soft references can be used to implement memory-sensitive caches.

And a soft reference can reference queue (Reference Queue) used in combination, if the soft reference the referenced object is garbage collected, Java virtual machine will be added to this soft references cited associated queue to the appropriate the timing of the recovery of soft references. However, due to a lower priority thread GC, usually manually call System.gc () does not perform GC immediately, so soft reference objects referenced not necessarily be immediately recovered.

Student student = new Student();
SoftReference SoftReference SoftReference = new (student);

Weak references (Weak Reference)

Weak reference represents an object in [may be useful, but not required] state. Similar to the soft references, but weaker strength than the soft reference number: The object has only a weak reference has a more short life cycle. GC thread during the scanning of the memory area under its jurisdiction, once an object has only a weak reference found, will recover out these objects are associated with weak references. In other words, regardless of whether the current shortage of memory, GC will be a weak recovery of the associated object reference. However, GC is a low priority thread, and therefore will not necessarily quickly find objects that have only a weak reference.

Weak references may also be cited, and a queue (Reference Queue) used in combination, if weak reference object referenced by the garbage collector, Java virtual machine will be added to this reference weak reference associated queue.

Student student = new Student();
WeakReference weakReference = new WeakReference(student);

Virtual reference (Phantom Reference)

Represents an object in a virtual reference [state] is useless. This means that there is no equivalent to the reference virtual reference, are likely to be recovered GC at any time. Provided virtual reference the purpose of the imaginary object is referenced at the time associated with the garbage collector is recovered, to receive a notification system (used to track objects recovered GC activity).

And the difference between the virtual reference that weak references: virtual reference must be used and the reference queue (Reference Queue) in combination.

ReferenceQueue referenceQueue = new ReferenceQueue();
PhantomReference phantomReference = new PhantomReference(object, queue);

This means, the GC in the recovery of an object, if it is found that the virtual object has a reference, it will be recovered before the first virtual object reference associated with a reference to the added queue. Program may be added whether the virtual reference queue to see whether the referenced object is to be recovered by GC determination reference. If the program finds a phantom reference has been added to the reference queue, then we can take the necessary action before it is recycled in memory referenced object.

Application: Use soft references build a cache of sensitive data

1. Why do you need to use soft references

First, we look at an example of a query employee information system. We will use employee information query system of a Java language to query the employee's personnel file information stored in the disk file or database. As a user, entirely possible we need to go back to see a few minutes ago, or even a few seconds ago Viewed employee file information (Similarly, we often use the back button in the browser when the WEB page).

Then we usually have two program implementation, one is the historical viewed employee information stored in memory, each storage lifecycle Java objects employee profile information throughout the application; the other is when user to start viewing the file information of other employees when the store employee file information currently viewed Java object references the end of that garbage collection thread can reclaim the memory space they occupy, when the user again, you need to file information to the employee when rebuilding information to the employee.

Obviously, the first implementation will result in a lot of memory wasted; and second defect realized that even if the object has not been garbage collection thread garbage collection, contains the employee profile information stored in the memory is still intact, the application but also to re-build an object (garbage collection thread is not immediate recovery). We know that access to disk files, access network resources, such as database query operations are important factors that affect the execution performance of the application, if they can retrieve Java objects that have not yet been recovered reference, will reduce unnecessary visits, greatly improve the operating speed of the program.

2. If using soft references

SoftReference is characterized by its soft to hold an instance of a Java object reference, the soft references exist without prejudice to the recovery of the garbage collection thread Java objects. That is, once the soft SoftReference save for a reference to the Java object, prior to garbage collection thread will recover this Java objects, classes provide SoftReference get () method returns a Java object of strong references. In addition, once garbage collection thread reclaim the Java objects, get () method will return null.

MyObject aRef = new MyObject();
SoftReference aSoftRef = new SoftReference (AREF); 

In the above code, for this new out MyObject objects, there are two reference paths, a soft SoftReference from a reference to the object from a reference variable aRef strong, so now the new target is out of a strong be MyObject and objects. We can then end aRef variable to its strong references:

aRef = null;

At this time, this new MyObject objects out of the can becomes soft and objects. If the garbage collector thread starts for memory garbage collection, and not because there is a reference to the object and SoftReference always retains the object. Java Virtual Machine garbage collection thread to be soft and objects, and other general Java objects are treated differently: can clean up the soft and the object is determined by the garbage collection thread algorithm according to their specific memory requirements. In other words, throw garbage collection thread will be recovered and soft objects before OutOfMemoryError, and virtual machine recovery as a priority target for an extended period of soft and can do in a virtual machine, and keep those just built or just used as much as possible the "new" softly reachable objects. So strong, before the recovery of these objects, we can regain the instance of an object by reference to the following code:

MyObject anotherRef = (MyObject)aSoftRef.get(); 

But if the instance of the object has been recycled garbage collection thread then calls the get () method can only get a null.

3. Use ReferenceQueue cleared lost soft reference object SoftReference

As a Java object, SoftReference soft reference objects in addition to saving the particularity outside, also has a general Java objects. So when the soft and the object can be recycled, although this may require SoftReference object's get () method returns null, but this is no longer the object of value SoftReference exist, the need for a proper clearance mechanisms, to avoid a large number of objects brought SoftReference memory leaks.

In java.lang.ref package also provides ReferenceQueue class. SoftReference when creating an object, you can use a ReferenceQueue object as a parameter to the constructor of SoftReference.

ReferenceQueue queue = new ReferenceQueue();
SoftReference ref = new SoftReference(aMyObject, queue); 

Thus, when an object instance while the soft references in this SoftReference recycled garbage collector, objects SoftReference the ref strong references will also be included in ReferenceQueue. In other words, the object is stored in ReferenceQueue Reference object, but the object it has lost Reference soft reference object. In addition ReferenceQueue can be seen from the name, it is a queue, when we call the poll it provides () method, if the queue is not empty queue, the queue will be returned in front of which Reference objects.

At any time, we can call the poll ReferenceQueue () method to check non-mandatory and that concern may be recovered. If the queue is empty, it returns a null, otherwise it will return a queue in front of the Reference object. Using this method, we can examine the object which SoftReference soft references has been recovered. So we can put these objects lose SoftReference soft reference object removed. Common ways are:

SoftReference ref = null;
while ((ref = (EmployeeRef) queue.poll()) != null) {
    // Clear ref
}

4. Use a soft reference summary

Because it is soft references used, then when viewed before you want to view employee information when you can re-create a strong association references to cancel the previously strong correlation, but have not yet been recovered thread garbage collection, store employee Java object information back to pick it up with, this is equivalent to doing a cache, the object is not only to avoid waste caused by the recovery of memory, you can also avoid creating new objects of consumption of resources (only the original object is garbage collection thread recovered, only you need to create a new object).

Guess you like

Origin www.cnblogs.com/cuiqq/p/11910352.html