Parsing Java object references and JVM Automatic Memory Management

Source: Internet
Author: User
Parse Java object reference and JVM Automatic Memory Management-Linux general technology-Linux programming and kernel information. The following is a detailed description. The application design interface for Object Reference is defined in JDKTM1.2. The application design interface allows the application to interact with the JVM Memory Manager in the form of object reference. When an application needs to manage a large number of memory objects or delete the original objects before creating a new Java object, the Java object reference application design interface has a considerable purpose. For example:

● Web-based applications often require a large number of images to be displayed. When a user leaves a Web page, it is often unable to determine whether a successful response can be made. In such a program, you can create an environment using the Java object reference API, that is, when the heap memory runs to a minimum, the memory manager creates an object. When the user returns, the application reloads the created image.

● The Application Object Reference queue can create such an environment. when an object is obtained through object reference, the application is notified. Then, the application can clear related objects and make these objects legal in the memory manager.


Working Mechanism of Memory Manager


The following describes the working mechanism of the memory manager when the referenced object is not embedded, and then discusses the changes in the Java heap after the referenced object is added.

The memory manager is used to identify objects that are no longer used in the program and reclaim the memory.

A Java application is composed of a series of threads, each thread executes a series of methods, and each method references objects through parameters or local variables. These references are part of the reference set and directly go to the application. In addition, the reference set includes static reference variables defined in the class library and references obtained through the Java Local interface (JNI) API. All referenced objects in the reference set can be obtained by the current application without being recycled. Similarly, these objects may contain references to other objects, which can also be obtained by the application, and so on. Other objects in the Java heap are considered unretrievable, and all these unretrievable objects are also valid in memory management. If an unrecoverable object uses the finalize () method, the task is handed over to the finalizer called by the object ). During the memory recycle period, objects that do not have an ending device cannot be obtained and objects that have called the ending device are simply recycled.

Memory collection algorithms are constantly changing. The common aspect is to identify available objects from the reference set and reclaim the memory space occupied by other objects.

The difference between a reference and a regular reference after a referenced object is that the reference in the referenced object is handled by the Memory Manager. Reference objects encapsulate references of other objects, which are called Directive objects. When a referenced object is created, the directive object of the referenced object is defined.

According to application requirements, objects can be any combination of strong references, soft references, weak references, and phantom references. To determine the availability of the object, the JVM Memory Manager starts from the reference set and finds all the paths to the object in the heap. When any path to an object does not contain referenced objects, the object is strongly accessible. When the path contains one or more referenced objects, the types of referenced objects queried by the Memory Manager are classified as secondary retrieval, weak retrieval, and virtual retrieval.

In addition, the reference object Queue (java. lang. ref. ReferenceQueue) is defined in the object reference API. This is a simple data structure managed by the Memory Manager to reference objects. It is worth noting that when defining a reference object, the phantom reference object must be generated in a reference object queue, and the soft reference and weak reference objects do not have this restriction, for example:

ReferenceQueue queue = new ReferenceQueue ();
PhantomReference pr = new PhantomReference (object, queue );

Soft References application instance


The following uses soft references in web-based applications as an example to describe how Java object references interact with the JVM Memory Manager.

When a user opens a web page, the applet code obtains the image and displays it. If the soft references of the image object is created in the Code, the memory manager Selects whether to recycle the memory allocated by the image when the user leaves the web page. When the user returns the webpage, The SoftReference. get method is used in the applet code to obtain the message indicating whether the image still exists in the memory. If this image is not created in the memory manager, it will be displayed on the web page soon; otherwise, the applet code will be retrieved again.

The following is the complete source code of Example. java.



Import java. awt. graphics; import java. awt. image; import java. applet. applet; import java. lang. ref. softReference; public class Example extends Applet {SoftReference sr = null; public void init () {System. out. println ("Initializing");} public void paint (Graphics g) {Image im = (sr = null )? Null: (Image) (sr. get (); if (im = null) {System. out. println ("Fetching image"); im = getImage (getCodeBase (), "yundong.gif"); sr = new SoftReference (im);} System. out. println ("Painting"); g. drawImage (im, 25, 25, this); g. drawString ("Beauty of motion", 20, 20); im = null;/* Clear the strong reference to the image */} public void start () {System. out. println ("Starting");} public void stop () {System. out. println ("Stopping ");}}


In the code above, the object image is an image object and is passed to a SoftReference object sr. Here, the image object is the sr indicator object, and the reference domain in the sr is from the soft reference to the image.


Weak References analysis


For a stable object, such as a thread-class object, it is ideal to apply weak references in the program to obtain external data. If the weak reference of a thread is created using the reference queue, the application will be notified when the thread no longer has strong access capabilities. Based on this notification, only applications can clear data objects.

When no strong references or soft references are found in the memory manager, it is called that the object has weak retrieval capability, that is, the path to the object contains at least one weak reference. After the weak references in the program is cleared for a period of time, the weak retrieval object is collected by the Terminator. We can also see that the difference between soft reference and weak reference is that when soft reference is applied, the memory manager uses algorithms to determine whether to create weak retrieval objects. When weak reference is applied, the memory manager must create an object to obtain the object.


Reference object chain


When the path to an object contains multiple referenced objects, a reference object chain is formed. The Memory Manager processes referenced objects in the order of strong to Weak. The specific processing steps include Soft references, Weak references, Finalization, Phantom references, and object creation.

When the memory manager does not find any reference to the first three objects, it means that the object has the virtual retrieval capability. That is, the path to the object contains at least one phantom reference. Virtual Reference objects are directly collected by the terminator without being recreated. When the memory manager finds that only phantom references are available, the object is waiting for phantom reference. The application sends a notification to the reference queue and then calls the clear () method to the virtual reference object, set its reference domain to null, and finally execute the collection and clearing task for unrecoverable objects.

Generally, an object has the same retrieval capability as the weakest connector in the direct path of the referenced object set. We can see that:

The virtual referenced object has a strong ability to obtain and other objects have a virtual ability to obtain;

(B) the virtual referenced object and weak referenced object in the medium have strong ability to acquire. Therefore, the secondary referenced object and the object set have the ability to obtain the weak referenced object;

(C) the virtual referenced object, weak referenced object, and secondary referenced object have strong acquisition capabilities, so the object set has the secondary acquisition capability.

● Using the reference object API in a program can not only control the memory manager to a certain extent, but also realize automatic memory management and improve the stability and security of the program.

● The acquisition capability of each object in the referenced object chain is related to the entire chain.
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.