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

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

黄舟
黄舟Original
2016-12-28 15:29:041278browse

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;

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);  
    }  
      
}

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;  
    }

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

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


Statement:
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