Comprehensive parsing of reference types in Java _java

Source: Internet
Author: User
Tags garbage collection int size memory usage

If an object in memory does not have any references, it means that the object is no longer in use and can be a candidate for garbage collection. However, the actual collection time of objects that can be garbage collected is indeterminate because the garbage collector's run-time is uncertain. For an object, as long as there is a reference to the existence, it will always exist in memory. If the number of such objects is increasing beyond the total amount of memory in the JVM, the JVM throws a outofmemory error. While the specific operation of garbage collection is controlled by the JVM, developers can still interact with the garbage collector to some extent, in order to better help the garbage collector manage the memory of the application. This interaction is the JAVA.LANG.REF package introduced using JDK 1.2.

1 Strong references
strong references are the most common references used. If an object has a strong reference, the garbage collector will never reclaim it. When memory space is low, the Java virtual machine would rather throw a outofmemoryerror error, cause the program to terminate abnormally, and not recycle the strongly referenced object to solve the out-of-memory problem.
As Date date = new Date (), date is a strong reference to an object. A strong reference to an object can be passed around in a program. In many cases, there are multiple references pointing to the same object at the same time. The presence of strong references limits the time that an object survives in memory. If object A contains a strong reference to object B, then in general, object B will not survive less than object A. If object A does not explicitly set object B's reference to NULL, then the object B will not have a reference to it until it is garbage collected, and then the opportunity for garbage collection is possible.
Instance code:

Package Com.skywang.java;

public class Strongreferencetest {public

 static void Main (string[] args) {
  mydate date = new MyDate ();
  System.GC ();
 }


Run Result:
< no output >
Result: date is not reclaimed even if garbage collection is explicitly invoked, but for date is a strong reference.
In addition to strong references, the JAVA.LANG.REF package provides a different way of referencing an object. The JVM's garbage collector has different ways of handling different types of references.

2 Soft References
if an object has only a soft reference, the memory space is sufficient, the garbage collector will not recycle it, and if the memory space is low, the memory of those objects is reclaimed. The object can be used by the program as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive caching.
A soft reference can be used in conjunction with a reference queue (Referencequeue), and the Java Virtual machine will add the soft reference to the reference queue associated with it if the object referenced by the soft reference is reclaimed by the garbage collector.
Soft references (soft reference) are weaker than strong references in strength, expressed by class SoftReference. Its role is to tell the garbage collector which objects in the program are less important and can be temporarily recycled when there is not enough memory. When there is not enough memory in the JVM, the garbage collector frees objects that are referred to only by soft references. If all these objects are released, the memory is not enough to throw a outofmemory error. Soft references are ideal for creating caches. When the system is low on memory, the contents of the cache can be freed. Consider an image editor program, for example. The program reads the entire contents of the image file into memory for easy processing. Users can also open multiple files at the same time. When there are too many files open at the same time, it can cause insufficient memory. If you use soft references to point to the contents of an image file, the garbage collector can reclaim the memory when necessary.
Instance code:

Package Com.skywang.java;

Import java.lang.ref.SoftReference;

public class Softreferencetest {public

 static void Main (string[] args) {
  SoftReference ref = new SoftReference (NE W mydate ());
  Referencetest.drainmemory ();
 }


Run Result:
< no output >
Results Note: Soft references are terminated when there is not enough memory. When a soft reference is prohibited,

SoftReference ref = new SoftReference (new MyDate ());
Referencetest.drainmemory ();

Equivalent to

MyDate date = new MyDate ();

The JVM decides to run
if (JVM. Out-of-memory ()) {
 date = null;
 System.GC ();
}

3 Weak references
Weak references (weak reference) are weaker than soft references in strength, expressed by class WeakReference. It does this by referencing an object, but does not prevent the object from being reclaimed. If a strong reference is used, the referenced object cannot be reclaimed as long as the reference exists. Weak references do not have this problem. When the garbage collector is running, if all references to an object are weak references, the object is reclaimed. Weak references are used to resolve the coupling relationship between objects that are brought by strong references in the survival time. The most common use of weak references is in the collection class, especially in the hash table. The interface of a hash table allows any Java object to be used as a key. When a key-value pair is placed in a hash table, the Hashtable object itself has a reference to those keys and value objects. If this reference is a strong reference, then as long as the hash table object itself survives, the key and value objects contained therein are not reclaimed. If a long surviving hash table contains a large number of key values, it may eventually consume all of the memory in the JVM.
The solution to this situation is to use weak references to refer to these objects, so that the key and value objects in the hash table can be garbage collected. Weakhashmap is provided in Java to meet this common requirement.
Sample code:

Package Com.skywang.java;

Import java.lang.ref.WeakReference;

public class Weakreferencetest {public

 static void Main (string[] args) {
  WeakReference ref = new WeakReference (NE W mydate ());
  System.GC (); 
 }


Run Result:

obj [date:1372142034360] is GC

Result: Weak references are terminated when the JVM garbage collection runs.

WeakReference ref = new WeakReference (new MyDate ());
System.GC ();

Equivalent to:

MyDate date = new MyDate ();

Garbage collection
if (JVM. Not enough memory ()) {
 date = null;
 System.GC ();
}

A weak reference differs from a soft reference in that an object that has only a weak reference has a more ephemeral lifecycle. When the garbage collector thread scans the area of memory it governs, it reclaims its memory whenever it discovers an object that has only a weak reference, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a very low priority thread, it is not necessarily easy to find those objects that have only weak references.
A weak reference can be used in conjunction with a reference queue (Referencequeue), and the Java virtual machine adds the weak reference to the reference queue associated with it if the object referenced by the weak reference is garbage collected.

4 false references
is also called Phantom Reference ~ before introducing the Phantom Reference, first introduce the object finalization mechanism (finalization) provided by Java. There is a Finalize method in the object class designed to perform some cleanup work before an object is actually recycled. Because Java does not provide the same mechanism as a C + + destructor, it is implemented through the Finalize method. But the problem is that the garbage collector's uptime is not fixed, so the actual elapsed time of these cleanup operations is unpredictable. Ghost references (phantom Reference) can solve this problem. You must specify a reference queue when creating a phantom reference phantomreference. When an object's Finalize method has been invoked, the Phantom reference of the object is added to the queue. By checking the contents of the queue, you know if an object is ready to be recycled.
Phantom references and their queues are rarely used, and are used primarily for finer memory usage control, which is significant for mobile devices. A program can then request memory to create a new object after it has determined that an object will be recycled. In this way, the memory consumed by the program can be kept in a relatively low quantity.
For example, the following code gives an implementation example of a buffer.

public class Phantombuffer {
 private byte[] data = new Byte[0];
 Private referencequeue<byte[]> queue = new referencequeue<byte[]> ();
 Private phantomreference<byte[]> ref = new Phantomreference<byte[]> (data, queue);
 Public byte[] Get (int size) {
  if (size <= 0) {
   throw new illegalargumentexception ("Wrong buffer size");
  }
  if (Data.length < size) {
   data = null;
   System.GC (); Forces the garbage collector
    to try {
    queue.remove ();//The method blocks until the queue is Non-empty
    ref.clear ();//phantom references are not automatically emptied, to manually run
    ref = NULL;
    data = new Byte[size];
    ref = new Phantomreference<byte[]> (data, queue);
   } catch (Interruptedexception e) {
    e.printstacktrace ();
   }
  }
  return data;
 }

In the code above, each time a new buffer is requested, the first is to ensure that the byte array of the previous buffer has been successfully reclaimed. The Remove method of the reference queue blocks until a new phantom reference is added to the queue. It should be noted, however, that this practice causes the garbage collector to run too many times and may cause the program to be too low on throughput.
Sample code:

Package Com.skywang.java;

Import Java.lang.ref.ReferenceQueue;
Import java.lang.ref.PhantomReference;

public class Phantomreferencetest {public

 static void Main (string[] args) {
  referencequeue queue = new REFERENCEQ Ueue ();
  Phantomreference ref = new Phantomreference (new MyDate (), queue);
  System.GC ();
 }


Run Result:

obj [date:1372142282558] is GC

Result Description: False references, after instantiation, are terminated.

Referencequeue queue = new Referencequeue ();
Phantomreference ref = new Phantomreference (new MyDate (), queue);
System.GC ();

Equivalent to:

MyDate date = new MyDate ();
date = null;

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.