Java 虚拟机主要可分为stack、heap、method area三个区域,其中栈主要用来存放基本类型变量,对象引用;堆主要存放类实例;方法区存放静态变量、静态方法、常量池。
1 栈的特点
(1) 栈用来描述方法执行的内存模型。每个方法被调用都会创建一个栈帧(存局部变量、操作数、方法出口);
(2) JVM 为每个线程创建一个栈,用于存放该线程执行方法的信息(实际参数、局部变量等);
(3) 栈属于线程私有,不能共享;
(4) 栈的存储特性,FIFO;
(5) 栈是由系统自动分配,速度快;栈是一个连续内存空间;
2 堆的特点
(1) 堆用于存储创建好的对象和数组;
(2) JVM 只有一个堆,被所有线程共享;
(3) 堆不是一个连续的内存空间,分配灵活,速度慢;
3 方法区
(1) JVM 只有一个方法区,被所有线程共享;
(2) 方法区实际上也是堆,用于存储类、常量相关信息;
(3) 堆用来存放程序中永远不变的内容,如类信息、静态变量、静态方法、字符串常量;
4 类运行过程中内存分析
(1) 类实例
package cn.latiny.normal; /** * @author Latiny * @version 1.0 * @description: Human * @date 2019/8/2 11:25 */ public class HumanDemo { public static void main(String[] args) throws Exception { Street street = new Street(); street.setName("中华路"); street.setNumber(10000); Location location = new Location("广东", "佛山", street); Human human = new Human(); human.setName("Latiny"); human.setAge(99); human.setLocation(location); System.out.println(human); } } class Humana { private String name; private int age; private Location location; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } @Override public String toString() { return "Human{" + "name='" + name + '\'' + ", age=" + age + ", location=" + location + '}'; } } class Locationa { private String province; private String city; private Street street; public Locationa(String province, String city, Street street){ this.province = province; this.city = city; this.street = street; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Street getStreet() { return street; } public void setStreet(Street street) { this.street = street; } @Override public String toString() { return "Location{" + "province='" + province + '\'' + ", city='" + city + '\'' + ", street=" + street + '}'; } } class Streeta { String name; int number; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Override public String toString() { return "Street{" + "name='" + name + '\'' + ", number=" + number + '}'; } }