What happened when new an object in JVM ?

原文链接:https://www.javaspring.net/java/what-happened-when-new-an-object-in-jvm

I. Introduction

As you know, Java is an object-oriented programming language. We usually use a variety of objects while writing code. So when you write

User user = new User();

such a line of code, what does the JVM do?

II. Understand the object

  1. Memory Layout

The memory layout of an object in the Hotspot virtual machine is divided into three parts: Object Header, Instance Data, and Alignment Padding.

  • The object header has two parts of information. The first part is used to store the running data of the object itself (HashCode, GC generation age, lock status flag, etc.). The other part is the type pointer, which points to its class metadata. The virtual machine uses this pointer to determine which instance of the class this object is (if there is a handle pool method there is no such thing). If it is an array, there will also be a record array length as shown in the following table:
Content Expression
Mark Word Object hashCode or lock information, etc.
Class Metadata Address Object type data pointer
Array length the length of the Array

Mark Word is a non-fixed data structure that stores as much information as possible in a very small space, and it multiplexes its own storage space based on the state of the object. The contents of the storage in each state are as follows:

Flag bit status storage content
01 Unlocked Object HashCode, age of generation
00 Lightweight lock Pointer to lock record
10 heavyweight lock Pointer to lock record
11 GC tag empty
01 biased biased thread ID, biased timestamp, object age
  • The instance data portion is the valid information that is actually stored, that is, the various types of field content defined in the code. Whether it is inherited by the parent class or in the child class.
  • Align padding does not have to exist, it only acts as a placeholder because the HotSpot virtual machine requires that the object‘s starting address must be an integer multiple of 8 bytes.

2.The object‘s access

In Java programs we manipulate an object by pointing to a reference to this object. We all know that the object exists in the heap, and this reference exists in the virtual machine stack. So how does the reference locate the location of the objects in the heap?

  • Direct pointer method (HotSpot implementation): The address stored directly in the reference is the address of the object in the heap. The advantage is that the positioning speed is fast, and the disadvantage is that the object movement (the object movement when the GC moves) itself needs to be modified.
  • Handle method: Part of the Java heap is used as a handle pool. The reference stores the handle address of the object, and the handle includes the specific location information of the object instance and type. The advantage is that object movement only changes the instance data pointer in the handle, the disadvantage is two positioning.
  1. The procession of creating an object
  • When the virtual machine encounters a new instruction, it checks whether the parameters of this instruction can locate a symbolic reference to a class in the constant pool and checks whether the represented class has been loaded by the class loader. If it is not loaded then the loading of this class must be performed first.
  • After the class load check is passed, the virtual machine will allocate memory for the new object, and the size of the memory required by the object can be determined after the class is loaded.
  • After the memory allocation is completed, the virtual machine needs to initialize the object to a value of zero, so that the instance variable of the object can be directly used without the initial value in the code. The class variable is initialized to a value of zero during the preparation phase of the class loading.
  • Set the necessary information for the object header, such as how to find the metadata information of the class, the hashCode of the object, the age of the GC, and so on.
  • After the above operation, a new object has been generated, but the method has not been executed, and all fields are zero. At this time, you need to execute the method (construction method) to initialize the object according to the programmer‘s wishes. The initialization operation of the class variable is completed in the initialization phase of the class loading method.

There are two ways to allocate memory:

  • The Java heap memory is regular (using a markup or a garbage collector with compression), using a pointer to the free location, and allocating memory moves the pointer equal to the allocated size.
  • The memory is not regular (the garbage collector using the markup cleanup), the virtual machine maintains a list of available memory blocks, and when the memory is allocated, a large enough memory space is found from the list to allocate the object and update the available memory list.
  • A GC is triggered when sufficient memory cannot be found

Concurrency problem solution when allocating memory:

Synchronize the actions of allocating memory space---use “the CAS failure retry” to ensure the atomicity of the update operation.
Each thread pre-allocates a small amount of memory in the heap, called the Thread Local Allocation Buffer (TLAB), which thread allocates memory on its TLAB, only when the TLAB runs out and allocates a new TLAB. Synchronization lock is required. Set by the -XX:+/-UseTLAB parameter.

  1. Create object instruction reordering problem
A a = new A();

A simple decomposition of an object:

  1. Allocate the memory space of the object
  2. Initialization object
  3. Set the reference to the allocated memory address

In the case of 2, 3 and 2 steps, the instruction reordering occurs, which causes problems when accessing the object before initialization in the case of multithreading. The “Double Detection Lock” mode of the singleton mode has this problem. You can use “volatile” to disable instruction reordering to solve problems.

原文链接:https://www.javaspring.net/java/what-happened-when-new-an-object-in-jvm

转载,请保留原文地址,谢谢 ~

原文地址:https://www.cnblogs.com/Alandre/p/11758003.html

时间: 2024-10-23 00:56:31

What happened when new an object in JVM ?的相关文章

Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

public class Test { public static void main(String[] args) { System.out.println(new CountingGenerator.String(12).next()); List<Integer> list=new ArrayList<Integer>(); list.add(new Integer(1)); list.add(new Integer(2)); Integer[] c = {1,3,3}; /

JVM - classLoader

此文参考:  http://www.cnblogs.com/liu-5525/p/5614425.html 1. classLoader 如何加载 class ClassLoader 负责将 .class 文件(可能在disk上,可能在网络上) 加载到 RAM 里面, 并为之生成对应的 [java.lang.Class] object. 当 JVM 启动的时候 会形成由三个 ClassLoader 组成的 初始类加载器 层次结构: bootstrap classloader --> extens

深入理解JVM虚拟机3:垃圾回收器详解

JVM GC基本原理与GC算法 微信公众号[Java技术江湖]一位阿里 Java 工程师的技术小站.作者黄小斜,专注 Java 相关技术:SSM.SpringBoot.MySQL.分布式.中间件.集群.Linux.网络.多线程,偶尔讲点Docker.ELK,同时也分享技术干货和学习经验,致力于Java全栈开发!(关注公众号后回复”Java“即可领取 Java基础.进阶.项目和架构师等免费学习资料,更有数据库.分布式.微服务等热门技术学习视频,内容丰富,兼顾原理和实践,另外也将赠送作者原创的Jav

【Scala】Scala之Classes and Properties

一.前言 前面学习了控制结构,下面学习Scala的Class和Properties. 二.Class&Properties 尽管Scala和Java很类似,但是对类的定义.类构造函数.字段可见性控制等则不相同,Java更为冗长,Scala精炼.本章将通过Scala的构造函数工作原理来理解Scala的类和字段,当申明类构造函数参数和使用var.val.private关键字来修饰类的字段时,Scala编译器将会为你生成代码,根据字段修饰符不同,Scala编译器会生成不同的存取函数,本章也会展示如何重

Java 经典问题

九种基本类型及封装类 基本类型 boolean byte char short int long double void 二进制位数 1 8(一字节) 16(2字节) 16(2字节) 32(4字节) 64(8字节) 64(8字节) -- 封装器类 Boolean Byte Character Short Integer Long Double Void switch语句后的控制表达式只能是short.char.int.long整数类型和枚举类型,不能是float,double和boolean类型

JavaScript Oriented[探究面向对象的JavaScript高级语言特性]

JavaScript Oriented 探究面向对象的JavaScript高级语言特性 Prologue . JavaScript Introduce 1.  JS Abstract JavaScript是由Netscape公司工程师Brendan Eich研发的脚本语言,经过推广和流行,兼容ECMA-262标准,至今用于描述HTML网页行为.(前端验证,检测,响应,触发,控制等动态行为) Knowledge Tree 2.     About Document 本文涉及到的概念有JavaScr

ReactNative 4Android源码分析二: 《JNI智能指针之实现篇》

文/Tamic http://blog.csdn.net/sk719887916/article/details/53462268 回顾 上一篇介绍了<ReactNative4Android源码分析2: JNI智能指针之介绍篇>JNI智能指针与wrapper class的作用,下面将对它们的具体实现进行分析,并解答上篇提出的几个问题 前文回顾了java object在JNI中的引用对象jobject的3种类型.智能指针自然也有相应的如下类型: global_ref 全局指针与jobject全局

博文目录

java基础 反射 注解 代理 泛型 异常 IO NIO Object类 JVM 内存模型 类加载机制 调优 Tomcat调优 java并发 JMM volatile synchronized lock AQS Condition 线程池原理 java集合 java集合架构概况 HashMap ArrayList LinkedList HashSet TreeSet HashTable 设计模式 设计模式总览,创建型,结构型,行为型 Spring spring IOC应用与原理,初始化机制,运行

Javascript Closures

Introduction The Resolution of Property Names on Objects Assignment of Values Reading of Values Identifier Resolution, Execution Contexts and Scope Chains The Execution Context Scope chains and [[scope]] Identifier Resolution Closures Automatic Garba