Strong, soft, weak, virtual references in Java

Source: Internet
Author: User
Tags object object

First, preface

Forget how to contact Java before the strong, soft, weak, virtual reference, and stupefied seems to be in the garbage collection, a little over these concepts ~ these knowledge in peacetime development use is really less (perhaps my level is not enough) ~ today will be finishing it ~

Second, the text

The understanding of these types of references in Java helps to understand the mechanism by which the JVM recycles memory. First, what do you do with the objects that they reference when the JVM performs garbage collection?

  1) Strong references, will not be collected at any time by the garbage collector, if the memory is not enough, preferring to throw outofmemoryerror.   2) Soft references are only recycled by the garbage collector when the memory is full, and if there is memory available, the garbage collector does not recycle.   3) weak references, as long as the garbage collector runs, will certainly be recycled, regardless of whether there is any available memory.   4) virtual references, virtual references are equal to no references, and can be garbage collected at any time.

After JDK1.2, Java extends the concept of references.

Here's a look at the four concepts of reference:

Strong reference (Strong Reference): refers to the common in the program code, similar to Object obj = new Object (), such a reference, as long as a strong reference is still present, the garbage collector would rather throw a outofmemory error, Objects that are referenced by a strong reference are not recycled

Soft Reference (Soft Reference): It is used to describe some objects that are useful but not necessary. For objects associated with soft references, these objects are then listed in the collection scope for a second collection before the system is about to occur with a memory overflow exception. If this collection does not have enough memory to throw a memory overflow exception, the virtual machine will ensure that all soft references (held objects) have been cleared before throwing outofmemoryerror, and that there is no constraint to guarantee that soft references (objects held) will be cleared at a particular point in time. or determine the order in which a different set of soft references (held objects) are purged. However, the specific implementation of the virtual machine will tend to not purge recently created or recently used soft references. After JDK1.2, the SoftReference class is provided to implement the soft reference. Soft references are ideal for caching, and when the system is low on memory, the contents of the cache can be freed:

Importjava.lang.ref.SoftReference;ImportJava.util.HashMap;ImportJava.util.Map; Public classTest {Private Staticmap<string, softreference> SQLCache =NewHashmap<>(); Private StaticObject Getfromchache (String sql) {SoftReference SR=sqlcache.get (SQL); Object Object= sr = =NULL?NULL: Sr.get (); if(Object = =NULL) {Object=getfromquery (SQL); Sqlcache.put (SQL,NewSoftReference (object)); }        returnobject; }         Private StaticObject getfromquery (String sql) {//query from database, slow.        if(condition) {
............. returnObject; } Else{ return NULL; } }}

Weak references (Weak Reference): are also used to describe non-required objects, but their strength is weaker than soft references, and objects associated with weak references can only survive until the next garbage collection occurs. When the garbage collector is working, the objects that are only referenced are reclaimed regardless of whether the current memory is sufficient. After JDK 1.2, the WeakReference class was provided to implement weak references. Weak references can be used where, when you want to reference an object, but this object has its own life cycle, you do not want to intervene in the life cycle of this object, you are using weak references. This reference does not have any additional impact on the object's garbage collection judgment (this can be answered from the "Object Accessibility" section later).

Virtual Reference (Phantom Reference): also known as a phantom reference or phantom reference, it is the weakest reference relationship. Whether an object has a virtual reference exists, does not affect its life cycle at all, and cannot obtain an object instance through a virtual reference. The only purpose of setting a virtual reference association for an object is to be able to receive a system notification when the object is reclaimed by the collector. After JDK1.2, a class is provided PhantomReference to implement a virtual reference. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can be understood by judging whether a virtual reference has been added to the reference queue.

Next, in garbage collection, the accessibility of objects is judged:

In garbage collection, in general, some references (such as soft, weak, virtual reference) or non-reachable objects for memory collection, when determining whether an object can be reached, first from the root set (Object object) to find, if there is no path to an object, then this object is "unreachable" object, will be recycled at the time of garbage collection. If there is a path to the situation, then it is necessary to determine the strength of the "up to" degree.

As shown, in this tree-shaped reference chain, the direction of the arrow represents the direction of the reference, and the object that is pointed to is the referenced object. As can be seen from the graph, from the root set to an object can be a number of paths. For example, the path to object 5 has ①-⑤,③-⑦ two paths. This leads to the question of how the accessibility of an object is judged:

Single Reference Path accessibility judgment: In this path, the weakest reference determines the accessibility of the object
Multiple reference Path accessibility judgments: The strongest reference in several paths determines the accessibility of the object

For example, we assume that the graph references ① and ③ as strong references, ⑤ as soft references, ⑦ as weak references, and for object 5 according to these two principles, the path ①-⑤ takes the weakest reference ⑤, so the path reference to object 5 is a soft reference. Similarly, ③-⑦ is a weak reference. The strongest reference is taken between the two paths, and object 5 is a soft-to-reach object.

third, the link

Http://www.cnblogs.com/yw-ah/p/5830458.html

https://my.oschina.net/ydsakyclguozi/blog/404389

Http://developer.51cto.com/art/200906/128189.htm

http://blog.csdn.net/luoyanglizi/article/details/51137704

http://blog.csdn.net/zhuojianhai88/article/details/13503007

http://blog.csdn.net/moxuelang/article/details/50762253

http://blog.csdn.net/lyfi01/article/details/6415726

Iv. Contact me

In order to facilitate the exchange of readers without the blog Park account, deliberately set up a penguin group (pure Public welfare, non-interest-related), if the reader is unclear about the blog, welcome Dabigatran Exchange: 261746360, Little dugbia-Blog Park

Strong, soft, weak, virtual references in Java

Related Article

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.