What happened when new an object in JVM ? (2)

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.

Create object instruction reordering problem

A a = new A();

A simple decomposition of an object:

Allocate the memory space of the object

Initialization object

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.heiqu.com/zydxfs.html