Four references in Java and examples of use of referencequeue and Weakhashmap

Source: Internet
Author: User
Tags whm

Introduction :

This article mainly introduces four kinds of references in Java: Strongreference (strong reference), Softreferenc (soft Reference), Weakreferenc (weak reference), Phantomreference (virtual Reference). We will also introduce the features and usage examples of referencequeue and Weakhashmap.

Welcome to discuss, if there are errors please correct me

if you want to reprint, please specify the source http://www.cnblogs.com/nullzx/

1. Four types of references in Java

In each of the four references, a soft reference, a reference, and a virtual reference require a related class to be created. You need to pass an object when you create it, and then get the real object by referring to the Get method.

1.1 strongreference ( Strong reference)

Strong references are the way we typically refer to an object in a program

Object obj = new Object ();

obj is a strong reference. The garbage collector never recycles it, and when there is not enough memory space,theJava virtual machine prefers to throw a outofmemoryerror error, causing the program to terminate abnormally, and not to recover from an out-of-memory problem by reclaiming a strongly referenced object.

1.2 softreference ( soft Reference)

Soft references are created with the help of the Softreferenc class under the Java.lang.ref package. When the JVM is garbage collected, the JVM reclaims only the space occupied by the object lock that the soft reference points to when there is not enough memory .

Package Javalearning;import java.lang.ref.softreference;/* * Virtual machine parameter configuration *-xms256m *-xmx1024m*/public class Softreferencedemo {public static void main (string[] args) {/* Soft-Reference object points to an array of 300 million-element-length arrays */softreference<int[] > softreference = new softreference<int[]> (new int[300000000]);/* actively invoke GC, because the JVM has enough memory at this time, At this point the object referenced by SoftReference is not recycled */system.gc (); System.out.println (Softreference.get ());/* consumes memory, resulting in an automatic GC, at which time the JVM's memory is not sufficient to reclaim the array object pointed to in the SoftReference object */int[] Strongreference = new int[100000000]; System.out.println (Softreference.get ());}}

Run results

[[Email Protected]null

1.3 WeakReference ( weak reference)

Soft references are created with the help of the Weakreferenc class under the Java.lang.ref package. When the JVM is garbage collected, objects that are associated only with weak references are reclaimed regardless of sufficient memory . Because the garbage collector is a very low-priority thread, it is not necessarily quick to discover those objects that are pointed to by weak references.

Package Javalearning;import Java.lang.ref.weakreference;public class Weakreferencedemo {public static void main (String [] args) {/* If the reference object points to a 1000-element-length-shaped array */weakreference<string[]> weakreference = new weakreference<string[] > (new string[1000]);/* does not perform GC, currently only the object pointed to by the weak reference has not been reclaimed, so the result is not NULL*/SYSTEM.OUT.PRINTLN (Weakreference.get ());/* Perform a GC once, Even if the current JVM has enough memory, it recycles only the objects pointed to by the weak reference */system.gc (); System.out.println (Weakreference.get ());}}

Run results

[Ljava.lang.string;@2a139a55null

1.4 plantomreference ( virtual Reference)

If an object holds only virtual references, it can be garbage collected at any time, just as there are no references. You must also pass a reference queue (Referencequeue) When you create a virtual reference object.

2. Introduction to Referencequeue (Reference queue)

When the GC (garbage collection thread) is ready to reclaim an object, if it finds that it has only a soft reference (or weak reference, or virtual reference) pointing to it, it adds the soft reference (or weak reference, or virtual reference) to the reference queue (Referencequeue) associated with it before it reclaims the object. If a soft reference (or weak reference, or virtual Reference) object itself is in the reference queue, it means that the object to which the reference object is pointing is recycled.

When a soft reference (or weak reference, or virtual Reference) object points to an object that is recycled, then the reference object itself is worthless, and if there is a large number of such objects in the program (note that the soft reference, the weak reference, the virtual reference object itself is a strong reference and is not automatically reclaimed by GC), the memory is wasted. So we can manually reclaim the reference object itself in the reference queue.

In addition to the way the above code shows the creation of reference objects. The creation of soft, weak, and virtual references has another way of associating a reference queue while creating a reference.

SoftReference (t referent, referencequeue<? super t> Q) weakreference (t referent, referencequeue<? super T> Q) Phantomreference (T referent, referencequeue<? super T> Q)

In the following example we use Referencequeue to reclaim the SoftReference object itself.

Package Javalearning;import Java.lang.ref.referencequeue;import Java.lang.ref.softreference;public class Referencequenedemo {@SuppressWarnings ({"Rawtypes", "Unchecked"}) public static void main (string[] args) {/* Create reference Queue */ Referencequeue<softreference<int[]>> RQ = new referencequeue<softreference<int[]>> ();/* Create a soft reference array, each object is a soft reference type */softreference<int[]>[] Srarr = new Softreference[1000];for (int i = 0; i < srarr.length; i++) {Srarr[i] = new SoftReference (new int[300000], RQ);} /* (possible) left three strong references in GC */int[] arr1 = Srarr[30].get (); int[] arr2 = Srarr[60].get (); int[] Arr3 = Srarr[90].get ();/* consumes memory, Causes a GC to be reclaimed only if the object pointed to by the soft reference is recycled */int[] strongref = new Int[200000000];object x;int n = 0;while ((x = Rq.poll ())! = null) {int IDX = 0;while (idx < srarr.length) {if (x = = Srarr[idx]) {System.out.println ("free" + x); Srarr[idx] = null; /* Manually free memory */n++;break;} idx++;}} /* Of course the simplest method is to determine whether a soft-referencing method is in the * queue by isenqueued (), the method above is just an example of int n = 0; for (int i = 0; i < srarr.length; i++) {if (srarr[i].isenquEued ()) {srarr[i] = null;n++;}} */SYSTEM.OUT.PRINTLN ("Recycle" + N + "SoftReference Object");}}

Run results (omit partial results)

... free [email protected]free [email protected]free [email] [email] [e-mail] [email protected] Recycle  997  softreference Object

As can be seen from the above example, the efficiency of recovering softreference objects is not very high. The reason is that every softreference reference taken out of the queue is the one we have to compare with each object in the softreference[] array. This way of finding is obviously less than hashmap, so we naturally think of building a reference type of HashMap to solve this problem. In fact, the JDK already provides a class with such a function, namely Weakhashmap.

3. Weakhashmap Introduction

Weakhahsmap the implementation of the principle is simply that the hashmap inside the entry Entry inherited WeakReference, then when the Entry key is no longer used (that is, the reference object is unreachable) and the GC, then the Entry will go to Referen The Cequeue. When we call Weakhashmap's get and put methods there is a side effect of clearing the invalid key corresponding to the entry. This process is similar to the code above, first the Entry object is fetched from the reference queue, then the location of the Entry object is found in the HashMap, and finally the Entry is removed from the HashMap, when both the key and the value object are recycled. Repeat this process until the queue is empty.

Finally, Weakhashmap is thread-safe.

Package Javalearning;import Java.util.weakhashmap;public class Weakhashmapdemo {public static void main (string[] args) { weakhashmap<string, byte[]> WHM = new weakhashmap<string, byte[]> (); string S1 = new String ("S1"); String s2 = new String ("S2");  String s3 = new String ("S3"), Whm.put (S1, New byte[100]), Whm.put (S2, new byte[100]), Whm.put (S3, New byte[100]); s2 = Null;s3 = null;/* may not have performed GC at this time, so it may also be possible to find Value*/system.out.println (Whm.get ("S1") with a key with only a weak reference; System.out.println (Whm.get ("S2")); System.out.println (Whm.get ("S3")); System.out.println ("-------------------");/* performs GC, which causes the entry (including value) of the key corresponding to the weak reference to be fully reclaimed */system.gc (); System.out.println (Whm.get ("S1")); System.out.println (Whm.get ("S2")); System.out.println (Whm.get ("S3"));}}

Run results

[Email protected][[email protected][[email protected]-------------------[[Email Protected]nullnull
4. Reference Content

[1] What is the use of strong references, soft references, weak references, and virtual references in Java?

[2] Use of Referencequeue

[3] Strong weak virtual---strong references, soft references, weak references, virtual references

Four references in Java and examples of use of referencequeue and Weakhashmap

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.