JVM Memory Management: A discussion (on the obj=null)

Source: Internet
Author: User
Tags arrays extend int size

You park friendly, LZ is from a site to move over the blogger, see here a lot of bloggers are said to see friends as a garden friend, LZ bold imitation, but before, LZ is actually said to see friends for ape friends. LZ in a Web site has already written a series of articles, has been copied to the park's new blog, mainly the content of the design model, you are interested can also go to look at, many of them are still quite popular with the ape friends loved.

As a program ape, the process of cultivation is like the protagonist in the fantasy novel, not only need to practice all kinds of martial arts, internal gas cultivation as important. Although the martial arts can quickly enhance the strength of the protagonist, but in the case of poor gas, the basic play does not show martial arts 10 of one or two.

Therefore, after introducing the design pattern of this kind of Wei Gong, LZ directly to the inner gas cultivation, and you ape friends to explore the content of the JVM.

This chapter should be about GC-related content, but before that, LZ is ready to discuss with you a little bit of programming skills. Of course, this tip is also closely related to GC.

I wonder if any of you ape friends have read some Java memory related articles, which are often written in such a way as to list the recommendations.

Article xx, after you have finished using the object, set the object to null.

That's not necessarily true, but it means the same thing. The meaning described in the words, that is, we should write code in the future should be so written.

Object obj = new Object ();
To do something 
obj = null;

This code is somewhat C + + style, Obj=null replaces delete obj or free (obj) in C/s + + + +, which is equivalent to prompting us, even if we have GC, we have to assign it as null if we finish using the object like no GC.

First of all, LZ here to illustrate that, to assign obj to a null value, and C + + in the delete is actually a difference, LZ said they replace the delete and free, simply because they appear in the code in a similar position.

The only thing that Obj=null did was to disconnect the reference variable of obj from the instance created by the new Object (), in fact, the memory space occupied by the instance was still not released.

In proposing this proposal, many bloggers or book authors (because there are many bloggers estimate also from the book) meant to eliminate references and instances as quickly as possible, thus inducing the GC to release the memory occupied by the instance when it was garbage collected. At some point, this is done to eliminate memory leaks.

LZ personally feel that many bloggers or book authors, put forward the original intention of this proposal, mainly for some no contact with the principle of GC and memory management of the program Ape and suggested, because in the absence of knowledge related to the premise, it is easy to grasp the scope of variables, This leads to unnecessary waste of memory (which is not the primary goal, because as long as no memory leaks occur, memory is eventually released by GC), or even memory leaks.

So for the sake of safety, some high people have made such a suggestion.

In view of this, LZ personally feel, after you have mastered the relevant knowledge, can completely ignore this suggestion, and this obviously will reduce the clarity of the code and increase the burden of coding, but the benefits, but only to avoid the non-existent memory leaks.

This explains why there are times when not assigning an object to a null value causes a memory leak, and we consider the following code.

Import Java.util.Arrays;
    
public class Stack {
        
    private static final int init_size = ten;
    
    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 length scalable stack implementation, you will find it is no problem when you write a test code to test it. But sorry, there is an obvious "memory leak" here, because some objects or references are not set to null values.

If you haven't seen it, LZ a little hint, and you'll realize it. In this code, the objects in the array will only grow infinitely, but will not decrease with the pop-up of the elements in the stack, only to reduce the size of the stack that is displayed externally. Consider an extreme scenario, assuming you've put 1 million objects into the stack, and finally used 999,999, and from the outside, there is only one available object left on the stack, but our stack still holds 1 million references to objects. If the JVM were to survive, it would surely have ravaged you to death.

What we lack is the step of assigning the object as a null value, so the pop method should be changed to the following way, and you can look at the source of the Remove method in ArrayList, which is similar to the idea.

Public Object pop () {
        if (size = = 0) {
            throw new indexoutofboundsexception ("size is zero");
        }
        Object data = datas[--size];
        Datas[size] = null;
        return data;
    }

This memory leak is very covert and is not necessarily found in actual use, because as the stack object is recycled, the entire array is recycled, and memory leaks are masked.

So personally feel that the above proposal is completely unnecessary, even if the above recommendations, if not familiar with memory management, will not think of the above code in the problem. If you want to completely avoid the memory leak, the mechanical initiative to assign the object to null value, is not a fundamentally solution to the problem.

The real solution to the problem is to master the strategy and principle of GC, to define a variable to pay more attention to the scope of variables, so as to better avoid memory leaks.

So it is necessary to learn the principle of GC. Hope to prepare to take the road of Java friends, especially from the training institutions out of the ape friends (here does not despise the training organization out of the ape friends meaning, because the LZ himself is also halfway decent, from the training institutions on the path of programming, one of the program ape), Be sure not to focus solely on the use of the frameworks and the depth of the business, although they are necessary, but not all.

Follow me and go to the memory world (grammar is a cloud).

Author: zuoxiaolong (Zao Jianrong)

Source: Blog Park Zao Jianrong Technology Blog--http://www.cnblogs.com/zuoxiaolong

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.