JAVA Memory Management Summary: Memory leaks, data storage, garbage collection mechanism catch!

Source: Internet
Author: User
Tags garbage collection wrapper advantage


1. How Java manages memory

Java's memory management is the issue of object allocation and deallocation. (Two parts)

Allocation: The allocation of memory is done by the program, and the programmer needs to request the memory space for each object through the keyword new (except for the base type), and all objects are allocated space in the heap (Heap).
Release: The release of an object is determined and executed by the garbage collection mechanism, which does simplify the programmer's work. But at the same time, it also aggravates the work of the JVM. Because, in order to properly release the object, the GC must monitor the running state of each object, including the object's application, reference, reference, assignment, and so on, which the GC needs to monitor.

2. What is called Java memory leak

In Java, a memory leak is the presence of some allocated objects, these objects have the following two characteristics, first of all, these objects are accessible, that is, in the direction diagram, the existence of the path can be connected with (that is, there is still a reference to the Memory object), and secondly, these objects are useless, that the program will not use these objects later. If the objects meet these two conditions, they can be judged as memory leaks in Java, which are not reclaimed by GC, but they occupy memory.

3. Component of the memory area of the JVM

Java is divided into two types of memory: one is stack memory, the other is heap memory 1. The primitive type variables and the reference variables of the objects defined in the function are allocated in the stack memory of the function; 2. Heap memory is used to hold objects and arrays created by new and the instance variables of an object when defining a variable in a function (code block). Java allocates memory space for this variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable. ; The memory allocated in the heap is managed by the Java Virtual machine's automatic garbage collector
Advantages and disadvantages of heap and stack

The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told to the compiler beforehand because it allocates memory dynamically at run time.

The disadvantage is to dynamically allocate memory at runtime, and access speed is slow; the advantage of the stack is that access is faster than the heap, second only to the registers directly located in the CPU.

In addition, stack data can be shared. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible.

4. How the data in Java is stored in memory

A) Basic data types

Java has a total of 8 basic data types, i.e. int, short, long, byte, float, double, Boolean, char (note that there is no basic type of string). This type of definition is defined by a form such as int a = 3; long B = 255L. such as int a = 3; Here's A is a reference to the int type, pointing to the 3 literal. These literal data, due to the size of known, lifetime known (these words are defined in a program block, the program block exit, the field value disappears), for the pursuit of speed reasons, exist in the stack.
In addition, the stack has a very important particularity, is the existence of the stack of data can be shared. For example: We also define:
int a=3;
int b = 3;
The compiler first deals with int a = 3; First, it creates a reference to a variable in the stack, and then looks for an address with a literal value of 3, then opens an address that holds the face value of 3 and then points a to 3. then the int b = 3 is processed, and after the B-reference variable is created, the B is pointed directly to the address of 3 because it already has 3 of the literal value on the stack.    In this way, there is a case where A and B both point to 3. After defining the value of a and B, then make a = 4; then, b is not equal to 4, or equal to 3. Inside the compiler, when encountered, it will search the stack for 4 literal values, if not, reopen the address to store the value of 4, and if so, point a directly to the address. Therefore the change of a value does not affect the value of B.

B) objects

In Java, create an object that includes the declaration and instantiation of an object, using an example to illustrate the object's memory model. Suppose that a class rectangle is defined as follows:
public class Rectangle {
Double width;
Double height;
Public Rectangle (Double w,double h) {
w = width;
h = height;
}
}
(1) The memory model when declaring an object
When an object rect is declared with rectangle rect, the memory space is allocated for the reference variable rect the object in stack memory, but the rectangle value is empty, and the rect is an empty object. A null object cannot be used because it does not yet reference any "entity".
(2) Memory model for object instantiation
When executing rect=new Rectangle (3,5);, two things are done: Width,height allocates memory for the class's member variable in heap memory and initializes it to the default value for each data type, followed by an explicit initialization (the initialization value when the class is defined), and the last call to the constructor method,  Assigns a value to a member variable. A reference to the object in the heap memory (equivalent to the first address) is rect to the reference variable, and the object in the heap memory can then be referenced by Rect.

c) Creating multiple different object instances

A class can create several different object instances by using the new operator, which will be allocated different memory spaces in the heap, and changing the state of one of the objects will not affect the state of other objects. For example:
Rectangle r1= New Rectangle (3,5);
Rectangle r2= New Rectangle (4,6);
At this point, the memory space is allocated to the member variable width and height of two objects in heap memory, and the space occupied by the two objects in the heap memory is different from each other. If there are:
Rectangle r1= New Rectangle (3,5);
Rectangle R2=r1;
Only one object instance is created in heap memory, two object references are created in stack memory, and two object references point to an object instance.

d) Packaging category

Basic types have corresponding packaging classes: such as int corresponding to the integer, double double, and so on, the basic type of definition is directly in the stack, if you use the wrapper class to create objects, just like ordinary objects.  For example: int i=0;i is stored directly in the stack. Integer I (I at this time is an object) = new Integer (5); Thus, the I object data is stored in the heap, the reference to I is stored on the stack, and the object is manipulated by reference in the stack.

e) String

A string is a special wrapper class data. Can be created in the following two ways: string str = new String ("abc"); string str = "ABC";
The first way to create a normal object is the same as the creation process;
The second way to create it is to translate this statement into the following steps within Java:
(1) First define an object reference variable named str to the String class: String str;
(2) in the stack to find there is no store value of "ABC" address, if not, then open up a storage word for "ABC"
Address, then create a new String Class object O and Point O's string value to this address, and on the stack
Next to this address, write down this referenced object o. If you already have an address with a value of "ABC", look for object o and
Back to O's address.
(3) Point Str to the address of object o.
It is noteworthy that the string values in the generic string class are stored directly. But like string str = "ABC";
Together, its string value holds a reference to the data in the existing stack.
To better illustrate this issue, we can verify this by using several of the following code.
String str1= "ABC";
String str2= "ABC";
System.out.println (S1==S2);//true
Note that str1.equals (STR2) is not used here, as this will compare the values of two strings for equality. The = = number, as described in the JDK, returns the true value only if two references are pointing to the same object. And what we're looking at here is whether str1 and str2 all point to the same object.
Let's look at the following code again.
String str1= new String ("abc");
String str2= "ABC";
System.out.println (STR1==STR2);//false
Two references were created. Two objects were created.     Two references point to different two objects. The above two pieces of code show that as long as the new object is created with new (), it is built in the heap and its string is stored separately, even if it is the same as the data in the stack, and is not shared with the data in the stack.

f) Array

When an array is defined, int x[], or int []x, an array reference is created in stack memory to refer to the array through that reference (that is, the array name). X=new int[3]; 3 spaces in heap memory that hold int data, the first address of heap memory is placed in the stack memory, and each array element is initialized to 0.

g) Static variables

The static-decorated variables and methods, in effect, specify the "fixed position"-static storage of these variables and methods in memory, and can be understood as the memory space shared by all instance objects. A static variable is somewhat similar to the concept of a global variable in C; It represents the sharing of memory, and every instance of it points to the same memory address.         The static is told to the JVM it is static, its reference (including indirect reference) is pointing to the same location, where you change it, it will not become the original, you clean it up, it will not come back. When was the static variable and the method initialized? For two different class attributes, the static property and the instance property, the timing of initialization is different.         The instance property is initialized when the instance is created, and the static property is initialized when the class is loaded, which is the first time the class is used, and is not initialized again for the creation of subsequent instances. We can often see examples like the following to illustrate this problem:
Class student{
static int numberofstudents=0;
Student ()
{
numberofstudents++;
}
}
Each time a new student instance is created, the member numberofstudents is incremented, and all student instances access the same numberofstudents variable, actually int The numberofstudents variable is stored in only one location in memory.

5. Java Memory Management Instance

  java multiple parts of a program (methods, variables, objects) reside in memory in the following two locations: Heap and Stack, now we only care about 3 kinds of things: instance variables, local variables, and objects:
Instance variables and objects reside on the heap
local variables reside on the stack
        Let's look at a Java program to see how his parts are created and mapped to stacks and heaps:
public class  dog {
Collar c;
string name; The
//1. main () method is on the stack
Public static void main (string[] args)  {
//2.  The reference variable d is created on the stack, but the Dog object does not already exist
Dog d;
3.  creates a new Dog object and assigns it to the D reference variable
D = new dog ();
4.  passes a copy of the reference variable to the Go () method
D.go (d);

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.