Talking about static methods and static properties and Java object References and JVM automatic memory management from the perspective of JVM memory management

Source: Internet
Author: User
Tags closure garbage collection instance method modifier thread class

Try to talk about static methods and static properties from the point of view of the JVM's memory management principles, please correct me where it is wrong. (joezheng123.javaeye.com/blog/264695)
The JVM's memory is divided into two parts: Stack and heap:

Stack (stack) is the memory instruction area of the JVM. Stack management is simple, push a certain length byte of data or instruction, stack pointer stack corresponding byte displacement; pop a certain byte length data or instruction, stack pointer Pinball. The stack is fast, management is simple, and the data or byte length of each operation is known. So Java basic data type, Java instruction code, constants are stored in stack.

The heap (heap) is the memory data area of the JVM. Heap's management is complex, allocating an indefinite amount of memory each time, specifically to hold an instance of the object. Allocating a certain amount of memory in the heap to save the object instance is actually just saving the object instance's property value, the attribute's type and the object's own type tag, and so on, does not save the object's method (the method is the instruction, saves in the stack), in heap A certain amount of memory is allocated in the Save object instance and the object's serialization comparison is similar. When an object instance is allocated in heap, a 4-byte heap memory address needs to be stored in the stack to locate the object instance in the heap, so that it is easy to find the object instance.

Because stack memory management is sequentially allocated, and fixed length, there is no memory recovery problem, and heap is random allocation of memory, indefinite length, there are memory allocation and recycling problems; so there is another GC process in the JVM that periodically scans heap, It scans heap from the 4-byte object address stored in the stack, locates the objects in heap, makes some optimizations (such as merging free memory blocks, and so on), and assumes that the areas not scanned in heap are idle. This is the process of garbage collection, with all the refresh (in effect, removing unwanted objects that have lost the object's address in the stack).

The first thing we need to figure out is what is data and what is instruction. Then figure out where the object's methods and objects ' properties are stored.

For ease of description, I am simply collectively:

1 The method itself is the operation code part of the instruction, which is stored in stack;

2 method Internal variables as the operands of the instruction, followed by the command code, stored in the stack (in fact, the simple type is stored in the stack, the object type in the stack to save the address, in the heap to save the value);

The above instruction operation code and the instruction operand constitute the complete Java instruction.

3 The object instance includes its property value as data and is stored in the data area heap.

Non-static object properties are stored in heap as part of an object instance, and object instances must be accessible through an address pointer saved in the stack. Therefore, the ability to access an object instance and its Non-static property values depends entirely on the availability of an object instance's address pointer in the stack.

First analyze the difference between non-static and static methods:

A non-static method has a significant difference from a static method: A Non-static method has an implied incoming parameter, which is given to it by the JVM, regardless of how we write the code, which is the address pointer of the object instance in the stack. Therefore non-static methods (instruction code in stack) can always find their own private data (object property values in heap). Of course, a non-static method must also obtain the implied parameter, so a non-static method must first get an instance of an object to obtain the address pointer in the stack before it is invoked, otherwise the JVM will not be able to pass the suppressed parameters to the Non-static method.

Static methods do not have this implied parameter, and therefore do not need a new object, as long as the class file is ClassLoader load into the JVM stack, the static method can be invoked. Of course, at this point the static method is not accessing the object properties in the heap.

Summarize the process: When a class file is ClassLoader load into the JVM, the method instruction is stored in the stack, and the heap area has no data at this time. Then the program technology to start the execution of instructions, if it is a static method, the direct execution of the instruction code, of course, this time the instruction code is not access to the heap data area, if the Non-static method, because the implied parameters do not have a value, will be an error. Therefore, before the Non-static method executes, the new object is first assigned, the data is allocated in the heap, and the address pointer in the stack is given to the Non-static method, so that the program technology executes the instruction sequentially, and the instruction code can access the heap data area at this time.

Again, static properties and Dynamic properties:

As mentioned earlier, object instances and dynamic properties are stored in heap, and heap must be accessible through the address pointer in the stack to the instruction (the method of the Class). It is therefore possible to infer that static properties are stored in the stack, unlike dynamic properties stored in heap. Because they are all in stack, and the instructions and data in the stack are fixed, it is easy to figure out the offsets, and therefore no matter what instruction (the method of the class) can access the static properties of the class. Also because static properties are stored in the stack, they have global properties.

To summarize: Static properties are stored in the stack instruction memory area, and dynamic properties are stored in the heap data memory area.

Added: 1. There is a pool of Word constants in Java, designed to store constants

2. The basic type is stored on the stack, for example:

int a=9; First in the stack to find whether there is this value, some words will refer to it, there is no words to create this value, and then point to the reference to it
3.

The stack is accessed faster than the registers in the CPU

But the size and lifetime of the data in it must be determined. Lack of flexibility generally used to store declared variables

Heap is slower than stack due to dynamically allocating memory to create object space

Also because the lifetime does not have to tell the compiler beforehand to be collected by GC

whether Java non-static methods share the same block of memory.

After a class has been generated for a instance, all instance field in this class will be added, and then all instance method will be added. The answer is no, we use field to represent the fields, we use method to represent the methods, then there are four of them after the static distinction:

Class field: field with a useful static modifier
Class method: A method with a useful static modifier
Instance field: Field not decorated with static
Instance method: No static Modified method

Then their representation in memory is:

Class field: Sharing a piece of memory
Class method: Sharing a piece of memory
Instance field: As each instance has a memory
Instance method: Share a piece of memory

If instance method also increases with instance, that memory consumption is too large, in order to achieve a small memory, Java is based on this keyword, such as: Instance1.instancemethod (); Instance2.instancemethod (); When passed to an object parameter, the Java compiler automatically adds a This parameter, which means that the object reference is passed, although the two objects share a method, but the data generated in their method is private, because the parameter is passed into the entry in call stack , and each object has a different call stack, so it's not confusing. In fact, when you call each non-static method, the Java compiler automatically adds the arguments that are currently calling this method object, and sometimes calls another method in one method, which you can not precede with this, because the object argument to pass is the object that currently executes the method.

Why a non-static method cannot be invoked in a static method. This is because the static method is directly related to class, and calling this method is called directly by the class, not an object, so the Java compiler has no object parameters to pass, so if you call a non-static method inside a static method, So how does the Java compiler determine which object the Non-static method is called. Yes, so the Java compiler will complain, but it is not absolute, the Java compiler is implicitly passing object parameters, then we can always display the passing object parameters, if we pass the reference of an object to the static method, You can then invoke non-static methods and access non-static data members through this reference.

parsing Java object References and JVM automatic memory management

The object reference Application design interface is newly defined in JDKTM1.2. The application design interface allows an application to interact with the JVM's memory manager in an object reference manner. Java object referencing application design interfaces are useful for applications that need to manage a large number of memory objects or delete existing objects before new Java objects are created, such as:

Web-based applications often require a large number of pictures to be displayed, and when a user leaves a Web page, it is often impossible to determine whether a successful return is possible. In this program, the Java object Reference API can be used to create an environment in which the memory manager creates objects when heap memory runs at a minimal level. When the user returns, the application will reload the picture that has been created.

Applying an object reference queue creates an environment in which the application is notified when an object is obtained from an object reference. The application can then purge the related objects and legitimize them in the memory manager.


The working mechanism of the memory manager


The following first describes how the memory manager works when a reference object is not embedded, and then discusses the changes that occur to the Java heap after the reference object joins.

The purpose of the memory manager is to identify objects that are no longer in use in the program and reclaim their memory.

A Java application consists of a series of threads, each executing a series of methods, and each method refers to the object by parameter or local variable. These references are part of the reference collection and go directly to the application. In addition, reference collections include static reference variables defined in the class library and references obtained through the Java Local interface (JNI) API. All referenced objects in a reference collection can be obtained by the current application without being reclaimed. Similarly, these objects may contain references to other objects, can be retrieved by the application, and so on. Other objects in the Java heap are considered not to be available, and all these objects that are not accessible are also valid in memory management. If an object that is not reachable uses the Finalize () method, the task is given to the finalizer that the object calls. During a memory recycle, an object that does not have a finish, and objects that have already called the end of the closure, are simply recycled.

The algorithm for memory recovery is constantly changing, and the common aspect is to identify the available objects from the reference collection and reclaim the memory space occupied by other objects.

The difference between a reference to a reference object and a regular reference is that the reference in the Reference object is handled exclusively by the memory manager. A reference object encapsulates a reference to some other object, which we call the indicator object. When a reference object is created, it also defines the indicated object for that reference object.

Depending on your application requirements, an object can be any combination of strong references (strong references), secondary references (soft references), weak references (weak references), virtual references (phantom references). To determine the availability of the object, the JVM memory manager sets out from the reference collection all the paths to the object in the heap. When any path to an object does not contain a reference object, the object is said to have strong ability to acquire, and when the path contains one or several reference objects, the type of the reference object queried by the memory manager is categorized as a secondary, weak, or virtual fetch.

In addition, the object reference API defines a Reference object queue (Java.lang.ref.ReferenceQueue), a simple data structure that the memory manager manages for reference objects. It is noteworthy that when making reference object definitions, it is required that phantom reference objects must be generated in a Reference object queue, while soft reference and weak reference objects do not have this restriction, such as:

Referencequeue queue = new Referencequeue ();
Phantomreference PR = new Phantomreference (object, queue);

Soft References Application Example


The following is an example of using soft references in a web-based application to illustrate the rationale for Java object references to interact with the JVM's memory manager.

When a user opens a Web page, the applet code gets the picture and is displayed. If the soft references of the picture object is created at the same time in your code, the memory manager chooses whether the memory allocated by the picture is recycled when the user leaves the Web page. When the user returns to the Web page, using the Softreference.get method in the applet code will get a message that the picture is still in memory. If the picture is not created in the memory manager, it will be displayed quickly on the Web page, otherwise the applet code will be retrieved again.

Here is the complete source code for 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"); void Paint (Graphics g) {Image im = (sr = null)? Null: (Image) (Sr.get ()); if (im = = null) {System.out.println ("Fetchin G image "); im = GetImage (GetCodeBase (), "yundong.gif"); sr = new SoftReference (IM); } System.out.println ("Painting"); G.drawimage (IM, A, this); g.DrawString ("The Beauty of Sport", 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 above code, object image is a picture object passed to an SoftReference object Sr. Where the image object is an indication object of the SR, the Reference field in the SR is from the secondary reference (soft reference) to image.


Analysis of Weak references


For a stable object, such as a thread class object, it is ideal to apply weak references in a program when it is necessary to obtain external data. If the weak reference of a thread is created with a reference queue, the application is notified that when the threads no longer have strong acquisition capability, the application can perform cleanup work on the related data objects according to this notification.

When the memory manager does not find strong references and soft references, we say that the object has a weak ability to acquire at least one weak reference in the path to the object. After the weak references in the program is cleared for a period of time, the weakly acquired object is collected by the closure. It can also be seen that the difference between soft reference and weak reference is that when the soft reference is applied, the memory manager uses the algorithm to determine whether to create a weak fetch object, and when weak reference is applied, The memory manager must create a secondary fetch object.


Reference Object Chain


When a path to an object contains more than one reference object, it forms a chain of reference objects. The memory Manager processes reference objects in a strong to weak order, including Soft references, Weak references, finalization, Phantom references, and creating objects in five parts.

When the memory manager does not find the first three object references, we say that the object has virtual access, that is, at least one phantom reference is included in the path to the object. A virtual Reference object is collected directly by the end of the collector and is not recreated. When the memory manager discovers that only phantom references, the object will be in a waiting phantom reference state, the application notifies the reference queue, and then calls the clear () method on the Virtual Reference object, setting its reference field to null. The Collection cleanup Processing task is finally performed on the unreachable object.

Typically, an object has the same acquisition capability as the weakest connector in the direct path of a reference object collection. It can be seen that:

The virtual Reference object has strong acquiring ability, and other objects have virtual acquisition ability;

(b) Both the virtual reference object and the weak reference object have strong acquiring ability, so the secondary reference object and the object set have the ability to acquire;

(c) The virtual reference object, the weak reference object, and the secondary reference object all have strong ability to acquire, then the object collection has the ability to acquire a secondary capability.

Using the Reference Object API in the program not only can control the memory manager to some extent, realize the memory automatic management, but also can improve the stability and security of the program.

The ability to acquire the objects in a chain of references 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.