Home Java javaTutorial JVM memory management------Miscellaneous talk (hereinafter also discuss obj=null)

JVM memory management------Miscellaneous talk (hereinafter also discuss obj=null)

Dec 28, 2016 pm 03:29 PM
JVM内存管理

As a programmer, the process of training is like the protagonist in a fantasy novel. Not only does he need to practice various martial arts, but the cultivation of inner energy is equally important. Although martial arts can quickly improve the protagonist's strength, if the inner energy is too low, it will not be able to exert one-tenth of the martial arts.
Therefore, after introducing external skills such as design patterns, LZ directly turned to internal Qi practice and discussed the contents of JVM with all ape friends.
Originally this chapter was supposed to introduce content related to GC, but before that, LZ is going to discuss a little programming trick with you. Of course, this little trick is actually closely related to GC.
I don’t know if any of you have read some articles related to JAVA memory. When listing suggestions, they often write out such a suggestion.
Article XX: After using the object, please explicitly set the object to null.
The original words may not be like this, but the meaning is the same. The meaning described in the words is that we should write this way when writing code in the future.

Object obj = new Object();  
//to do something   
obj = null;
Copy after login

This code has a bit of C/C++ style. obj=null replaces delete obj or free(obj) in C/C++, which is equivalent to reminding us that even with GC, we still need to Just like without GC, the object must be assigned a null value after use.
First of all, what LZ wants to explain here is that assigning obj to a null value is actually very different from delete in C/C++. The reason why LZ says that they replace delete and free is just because they appear in the code. The positions in are just similar.
obj=null only does one thing, which is to disconnect the reference variable obj from the instance created by new Object(). In fact, the memory space occupied by the instance is still not released.
When this suggestion was made, the original intention of many bloggers or book authors (because many bloggers probably read it from books) was to eliminate the association between references and instances as soon as possible, thereby inducing GC to proceed. During garbage collection, the memory occupied by the instance is released. In some cases, this is also done to eliminate memory leaks.
LZ personally feels that the original intention of many bloggers or book authors to make this suggestion is mainly for programmers who have not been exposed to GC principles and memory management, because without understanding the relevant knowledge, It is easy to fail to grasp the scope of variables, which leads to unnecessary waste of memory (I personally feel that this is not the main purpose, because as long as no memory leak occurs, the memory will eventually be released by GC), or even memory leaks.
So for the sake of safety, some experts made such a suggestion.
In view of this, LZ personally feels that after everyone has mastered the relevant knowledge, you can completely ignore this suggestion, and doing so will obviously reduce the clarity of the code and increase the burden of coding. However, the benefits in exchange are only In order to avoid memory leaks that may not even exist.
Here is an explanation of why not assigning an object a null value in some cases will cause a memory leak. Let's consider the following piece of code.

import java.util.Arrays;  
public class Stack {  
      
    private static final int INIT_SIZE = 10;  
    private Object[] datas;  
      
    private int size;  
    public Stack() {  
        super();  
        datas = new Object[INIT_SIZE];  
    }  
      
    public void push(Object data){  
        if (size == datas.length) {  
            extend();  
        }  
        datas[size++] = data;  
    }  
      
    public Object pop(){  
        if (size == 0) {  
            throw new IndexOutOfBoundsException("size is zero");  
        }  
        return datas[--size];  
    }  
      
    private void extend(){  
        datas = Arrays.copyOf(datas, 2 * size + 1);  
    }  
      
}
Copy after login

This code is a simple stack implementation with scalable length. When you write a test code to test it, you will find that there is no problem with it. But sorry, there is an obvious "memory leak" here, which is caused by some objects or references not being set to null values.
If you haven’t seen it yet, LZ will give you a little reminder and you will realize it. In this code, the objects in the array will only grow infinitely, and will not decrease as the elements in the stack are popped. What decreases is only the size of the stack displayed externally. Consider an extreme scenario. Suppose you have put 1 million objects into the stack, and finally 999,999 are used. From the outside, there is only one available object left in the stack, but Our stack still holds references to 1 million objects. If the JVM could survive, it would definitely ravage you to death.
What we lack is the step of assigning the object to a null value, so the pop method should be changed to the following method, and you can take a look at the source code of the remove method in ArrayList, which has a similar idea.

public Object pop(){  
        if (size == 0) {  
            throw new IndexOutOfBoundsException("size is zero");  
        }  
        Object data = datas[--size];  
        datas[size] = null;  
        return data;  
    }
Copy after login

这个内存泄露是非常隐蔽的,而且实际使用当中不一定就能发现,因为随着Stack对象的回收,整个数组也会被回收,到时内存泄露就被掩盖了。
所以个人觉得上述的那个建议是完全没有必要的,就算遵从了上面的建议,如果对内存管理不熟悉的话,也不会想到上面这个代码中的问题。如果想彻底的避免内存泄露的发生,机械式的主动将对象赋为空值,并不是一个可以从根本上解决问题的办法。
真正能够解决问题的办法,就是掌握好GC的策略与原理,定义一个变量时多注意变量的作用域,如此才可以更好的避免内存泄露。
所以学好GC原理还是很有必要的,希望准备走JAVA之路的朋友,尤其是从培训机构出来的猿友们(此处没有鄙视培训机构出来的猿友们的意思,因为LZ本人也是半路出家,从培训机构走上编程之路的程序猿之一),一定不要只专注于各个框架的使用以及业务的深入,虽然这些事很有必要,但并不是全部。
follow me and go the memory world 吧(语法都是浮云)。

 以上就是JVM内存管理------杂谈(借此也论一论obj=null)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles