About the memory distribution of JAVA programs

Table of contents

1. Memory description when Java program is running

2.JVM memory division

3.Data types in Java

4.String in Java

5. Combined with HelloWorld to analyze the memory distribution of java program


1. Memory description when Java program is running

          The written .java program file needs to be converted into a .class file by the java compiler javac, and then the .class file is loaded and executed through jvm (an executable program named java). Every time a java program is run, an instance of java (JVM) is generated. A java process corresponds to a JVM instance, which may contain one or more threads. Each JVM instance has a corresponding heap, and each thread has its own private stack. The corresponding arrays of all classes created by the process are stored on the heap and are shared by all threads of the process. Allocating memory for an object on the heap in Java will initialize the variables in this object. References to objects on the heap are allocated on the stack. To create an object, memory is allocated on both the heap and the stack. The memory allocated on the heap stores the object itself, while the memory allocated on the stack only stores references to the heap object. When a local variable is new in the function stack frame, space is allocated in the stack space and heap space. When the life cycle of the local variable ends, the stack space is immediately recycled, and the heap space area waits for GC recycling.

2.JVM memory division

The memory of JVM can be divided into 3 areas: heap, stack and method area (method, also called static area):

Heap area: 
(1) All objects are stored, and each object contains information about a corresponding class (the purpose of class is to obtain operation instructions); (2)
JVM has only one heap area (heap), and it is owned by Thread sharing, basic types and object references are not stored in the heap, only the object itself and the array itself are stored;

Stack area: 
(1) Each thread contains a stack area, and only the basic data type itself and references to custom objects are saved in the stack; (
2) The data in each stack (original types and object references) are private. Other stacks cannot be accessed;
(3) The stack is divided into 3 parts: basic type variable area, execution environment context, and operation instruction area (storage operation instructions);

Method area (static area): 
(1) Shared by all threads, the method area contains all classes (class refers to the original code of the class. To create an object of a class, the code of the class must first be loaded into the method area , and initialized) and static variables. 
(2) The method area contains elements that are always unique in the entire program, such as class and static variables. 
The difference between heap and stack:
(1) Both stack and heap are places used by Java to store data. Unlike C++, Java automatically manages the stack and heap, and programmers cannot directly set the stack or heap. 
(2) The advantage of the stack is that the access speed is faster than the heap, second only to the registers directly located in the CPU. But the disadvantage is that the size and lifetime of the data stored in the stack must be determined and there is a lack of flexibility.
The advantage of the heap is that it can dynamically allocate memory size, and the lifetime does not need to be told to the compiler in advance. Java's garbage collector will automatically collect the data that is no longer used.
But the disadvantage is that due to the dynamic allocation of memory at runtime, the access speed is slow.

3.Data types in Java

(1) Basic types (primitive types), there are 8 categories in total, namely int, short, long, byte, float, double, boolean, char.
This type of definition is defined in the form such as int a = 3; long b = 255L; and is called an automatic variable. Automatic variables store literal values, not instances of the class,
that is, they are not references to the class. There is no class here. For example, int a = 3; where a is a reference pointing to type int, pointing to the literal value 3.
Since the data of these literal values ​​are known in size and lifetime (these literal values ​​are fixedly defined in a certain program block, and the field values ​​disappear after the program block exits), for the sake of speed, they exist on the stack. . 
(2) Packaging class data, such as Integer, String, Double and other classes that wrap the corresponding basic data types.
All these types of data exist in the heap. Java uses the new() statement to explicitly tell the compiler that it will be dynamically created as needed at runtime, so it is more flexible, but the disadvantage is that it takes up more time. 
(3) Custom data types
are created using the new() statement. The objects are stored in the heap area and used through references in the stack area.

4.String in Java

(1) The shared characteristics of the stack
String str1 = "abc";
String str2 = "abc";
System.out.println(str1==str2); //true
description:
1) The compiler first processes String str1 = "abc" ; It will create a reference to the variable str1 in the stack, and then search whether there is abc value in the stack. If not found, it will store abc in, and then point str1 to abc.
2) Then process String str2 = "abc"; after creating the reference variable of b, because the value abc already exists on the stack, str2 will be pointed directly to abc. In this way, there is a situation where str1 and str2 both point to abc at the same time.
So when we define a class using a format such as String str = "abc";, we always take it for granted that the object str of the String class is created. In fact, the object may not be created (created on the stack), but may just point to a previously created object.
(2) Heap memory
The new() method can ensure that a new object is created every time. It is stored on the heap. Due to the immutable nature of the String class, when a String variable needs to frequently change its value, you should consider using the StringBuffer class
to improve program efficiency.

5. Combined with HelloWorld to analyze the memory distribution of java program

HelloWorld.java

//import java.lang.Integer;

public class HelloWorld {  //运行时jvm 把HelloWorld的代码全部都放入方法区     
    public static void main(String[] args) {  //main方法放在方法区
        System.out.println("Hello World!");
		Student stu = new Student(110, "Andy", 18);  //stu在栈上,引用堆上new出来的对象,new Student(110, "Andy", 18)在堆上存储
		stu.printStudent();
		int[] iArr = new int[10]; //iArr在栈上,引用堆上new出来的对象,new int[10]在堆上存储
		for (int i = 0; i < 10; i++) {
			iArr[i] = i;
		}
		System.out.println("iArr: " + iArr);
		int[] iArr1 = {12, 34, 45, 60, 45, 82};
		System.out.println("iArr: " + iArr1);
    }
}

class Student { //运行时jvm 把Student的代码全部都放入方法区   
private int id;
private String name;
private Integer age;   
    
public Student(int id, String name, Integer age) {     
	this.id = id;
	this.name = name;
	this.age = age;
}     
   
   
public void  printStudent() { //printStudent方法放在方法区
	System.out.println("id: " + id); 
	System.out.println("name: " + name); 
	System.out.println("age: " + age); 
}  
   
}

Compile and run:

Decompile bytecode:

javap -v HelloWorld.class

  Remarks: Error [Error: Unmappable character encoding GBK] solution

Reason for the error: The default character set under Windows is: GBK, and when the Chinese characters in your java file are not in the character set: GBK, javac will report an error when compiling.

Solution:

(1) javac specifies the file encoding method, for example

javac -encoding UTF-8 HelloWorld.java

(2) Set the file encoding to GBK encoding

Guess you like

Origin blog.csdn.net/hsy12342611/article/details/132514800