Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to interpret the object Life cycle in JVM

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to interpret the life cycle of objects in JVM. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

In the JVM runtime space, the whole life cycle of an object can be roughly divided into seven phases: creation phase (Creation), application phase (Using), invisible phase (Invisible), unreachable phase (Unreachable), collectable phase (Collected), termination phase (Finalized) and release phase (Free). The above seven phases constitute the complete life cycle of objects in JVM. The following describes the different situations when the object is in these seven stages.

Creation Pha

During the object creation phase, the system completes the object creation process through the following steps:

(1) allocate storage space for objects.

(2) begin to construct objects.

(3) Recursively call the constructor of its superclass.

(4) initialize object instance and variable.

(5) execute the body of the construction method.

Step 3 of the above five steps refers to recursively calling the constructor of all the parent classes extended by the class. A Java class (except the Object class) has at least one parent class (Object), which is both mandatory and implicit. You may have noticed that when creating a Java class, an Object parent class is not explicitly declared to extend (extends). In fact, in Java programming, any Java class is directly or indirectly a subclass of the Object class. For example, the following code:

Public class A {... } this statement is equivalent to the following statement: public class An extends java.lang.Object {… }

The above explains some of the processing work done by the system when the object is in the creation stage, some of which are closely related to the performance of the application, so when creating objects, we should follow some basic rules to improve the performance of the application.

Here are a few key rules to apply when creating objects:

(1) avoid creating an object in the body of a loop, even if it takes up a small amount of memory space.

(2) make the object meet the garbage collection standard as soon as possible.

(3) do not adopt too deep inheritance level.

(4) accessing local variables is better than accessing variables in the class.

With regard to rule (1) to avoid creating an object in the body of a loop, even if the object takes up a small amount of memory space, we need to be reminded that this situation is often encountered in our practical application, and we are easy to make similar mistakes, such as the following code:

... ... For (int I = 0; I

< 10000; ++i) { Object obj = new Object(); System.out.println("obj= "+ obj); } … … 上面代码的书写方式相信对你来说不会陌生,也许在以前的应用开发中你也这样做过,尤其是在枚举一个Vector对象中的对象元素的操作中经常会这样书写,但这却违反了上述规则(1),因为这样会浪费较大的内存空间,正确的方法如下所示: … … Object obj = null; for (int i = 0; i < 10000; ++i) { obj = new Object(); System.out.println("obj= "+ obj); } … … 采用上面的第二种编写方式,仅在内存中保存一份对该对象的引用,而不像上面的***种编写方式中代码会在内存中产生大量的对象应用,浪费大量的内存空间,而且增大了系统做垃圾回收的负荷。因此在循环体中声明创建对象的编写方式应该尽量避免。 另外,不要对一个对象进行多次初始化,这同样会带来较大的内存开销,降低系统性能,如: public class A { private Hashtable table = new Hashtable (); public A() { // 将Hashtable对象table初始化了两次 table = new Hashtable(); } } 正确的方式为: public class B { private Hashtable table = new Hashtable (); public B() { } } 不要小看这个差别,它却使应用软件的性能相差甚远,如图2-5所示。

Figure 2-5 performance differences caused by initializing objects multiple times

It seems that the old motto "Don't do bad things even if it is inconspicuous" should be followed in programming, otherwise the application we have developed is also inefficient, and sometimes a tiny mistake in the application software will greatly reduce the performance of the whole system. Therefore, in our daily application development, we should take every line of code seriously, write it in a * * way, don't ignore the details, and don't ignore potential problems.

Application stage

When the creation phase of an object is over, the object usually enters the application phase of the object. This stage is the stage in which the object is able to show his or her ability. In other words, the application stage of the object is the period in which the object proves its "existence value" in the whole life cycle. During the application phase of an object, an object has the following characteristics:

The ◆ system maintains at least one strong reference to the object (Strong Reference)

All references to this object in ◆ are strong references (unless we explicitly use: soft references (Soft Reference), weak references (Weak Reference), or virtual references (Phantom Reference)).

Several different reference types are mentioned above. Perhaps some readers are not very clear about the concepts of these citations, which are introduced below. Before we can explain these different types of references, we must first understand the structural hierarchy of object references in Java.

The structural hierarchy of the Java object reference is shown in figure 2-6.

Figure 2-6 A hierarchical representation of object references

From figure 2-6, it is not difficult to see the hierarchical relationship of several references mentioned above, with strong references at the top and virtual references at the bottom. The following are introduced respectively.

1. Strong reference

Strong Reference means that the JVM memory manager searches all the paths to objects in the heap from the root reference collection (Root Set). When any path to an object does not contain a reference object, a reference to that object is called a strong reference.

2. Soft reference

The main feature of soft citation (Soft Reference) is its strong citation function. This type of memory is reclaimed only when there is not enough memory, so when there is enough memory, they are usually not recycled. In addition, these reference objects are guaranteed to be set to null before Java throws an OutOfMemory exception. It can be used to cache some commonly used resources, achieve the function of Cache, and ensure the limited use of memory without causing OutOfMemory. Furthermore, all soft references to the soft reachable object are guaranteed to be cleared before the virtual machine throws the OutOfMemoryError. Otherwise, the time to clear soft references or the order in which a set of such references for different objects is cleared will not be subject to any constraints. However, virtual machine implementations do not encourage clearing recently accessed or used soft references. The following is the implementation code for the soft reference:

... ... Import java.lang.ref.SoftReference;... An a = new A (); … / / use a … / / after using a, set it to the soft reference type and release the strong reference; SoftReference sr = new SoftReference (a); a = null;... / / if (sringing null) {a = sr.get ();} else {/ / GC may have been reclaimed by the system due to insufficient memory resources, so it needs to be reloaded. A = new A (); sr=new SoftReference (a);}... ...

With the introduction of soft reference technology, Java applications can better manage memory, stabilize the system, prevent system memory overflow and avoid system crash (crash). Therefore, you should try to apply this technique when dealing with objects that take up a large amount of memory and have a long declaration period, but are used infrequently. Just like the above code, we can recreate objects after they are recycled (in this case, those objects that do not retain the running state) to improve the application's efficient use of memory and improve system stability. But things always have two sides, both advantages and disadvantages. In some cases, the use of soft references will reduce the running efficiency and performance of the application, for example, the initialization process of the object with soft reference is more time-consuming, or the state of the object changes during the running of the program. it will bring varying degrees of trouble to recreate the object and initialize the object, and sometimes we have to weigh the pros and cons.

3. Weak reference

The difference between weak reference (Weak Reference) objects and Soft reference objects is that GC needs to check whether Soft reference objects are recycled by algorithm, while for Weak reference objects, GC always does. As a result, Weak reference objects are easier and faster to be recycled by GC. Although GC must recycle Weak reference objects at run time, complex relational Weak object groups often require several GC runs to complete. Weak reference objects are often used in Map data structures to reference objects that take up a large amount of memory. Once the strong reference to the object is null, the reference to the object no longer exists, and GC can quickly reclaim the object space. Similar to soft references, we can also give the corresponding application code:

... ... Import java.lang.ref.WeakReference;... An a = new A (); … / / use a … / / after using a, set it to the weak reference type and release the strong reference; WeakReference wr = new WeakReference (a); a = null;... / / when using if next time, {a = wr.get ();} else {a = new A (); wr = new WeakReference (a);} … ...

The weak reference technique is mainly suitable for implementing normalized mappings that cannot prevent their keys (or values) from being recycled. In addition, weak references are divided into "short weak references (Short Week Reference)" and "long weak references (Long Week Reference)". The difference is that long and weak references still track the object after the object's Finalize method is called by GC. For security reasons, long and weak references are not recommended. Therefore, it is recommended that you create a weak reference to an object in the following way.

... ... WeakReference wr = new WeakReference (obj); or WeakReference wr = new WeakReference (obj, false); … ...

4. Virtual reference

Virtual references (Phantom Reference) are less useful and are mainly used to assist the use of finalize functions. Phantom objects refer to objects that have finished executing finalize functions and are unreachable objects that have not yet been reclaimed by GC. This kind of object can assist finalize to do some later recycling work, and we enhance the flexibility of the resource recovery mechanism by overriding the clear () method of Reference. Virtual references are mainly suitable for scheduling pre-mortem cleanup operations in a more flexible way than the java termination mechanism.

Note that weak references and virtual references are rarely used in actual programming, and soft references are often used, because soft references can accelerate the collection of junk memory by JVM, maintain the security of the system and prevent memory overflow (OutOfMemory) and other problems.

Invisible phase

After an object has gone through the application phase, then the object is in the invisible phase, which means that we can no longer reference it in the code in other areas, and its strong reference has disappeared, for example, the local variable is out of its visual range, as shown below.

... ... Public void process () {try {Object obj = new Object (); obj.doSomething ();} catch (Exception e) {e.printStackTrace ();} while (isLoop) {/ /. Loops forever / / this area is already invisible to obj objects / / so the following code throws an error obj.doSomething ();}} at compile time. ...

If an object has been used up and is no longer used in its visual area, you should actively set it to null at this time. You can add a line of code such as obj = null;, under the above line of code obj.doSomething (); to force the obj object to be null. The significance of this is that it can help JVM find the junk object in time and reclaim the system resources occupied by the object in a timely manner.

Unreachable phase

Objects in the unreachable phase can no longer find direct or indirect strong references in the root set of object references managed by the virtual machine. These objects usually refer to temporary variables in all thread stacks, static variables of all loaded classes, or references to native code interfaces (JNI). These objects are prepared objects to be reclaimed by the garbage collector, but at this time the object cannot be directly recycled by the garbage collector. In fact, all garbage collection algorithms face the same problem-finding blocks of memory that are allocated by the allocator but not reachable by the user program.

Collectable phase, final phase and release phase

One of the phases of the object life cycle is the collectable phase, the terminal phase, and the release phase. When an object is at this stage, it may be in the following three situations:

(1) the garbage collector finds that the object is unreachable.

(2) the finalize method has been executed.

(3) object space has been reused.

When the object is in the above three cases, the object is in the collectable phase, the final phase, and the release phase. The virtual machine can recycle the object directly.

On how to interpret the life cycle of objects in JVM to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report