Detailed explanation of JVM object creation and access positioning process
Dec 08, 2020 pm 05:50 PMjava Basic TutorialThe column introduces the process of JVM creating objects and accessing positioning
Related free learning recommendations: java basics Tutorial
1. Object creation
- When the virtual machine receives the new instruction, it checks whether this instruction can locate a class symbol in the constant pool. reference, and checks whether the class represented by this symbolic reference has been loaded, resolved, and initialized. If there are none, perform the class loading process first.
- After the class loading is passed, the virtual machine allocates memory for the new object (dividing a memory of a certain size from the Java heap). The memory size can be completely determined after the class loading is completed.
- Two allocation methods:
- (1): Pointer collision: Assume that the memory in the Java heap is absolutely regular, that is, the used memory is on one side, the free memory is on the other side, and the middle A pointer is placed as an indicator, and memory allocation is achieved by moving the pointer.
- (2): Free list: If the memory in the Java heap is not regular, that is, used memory and free memory are interleaved, the virtual machine must maintain a list to record which memory blocks are available. , allocates memory by finding space from the list to allocate to object instances.
- Whether the Java heap is regular or not is determined by whether the garbage collector used has a compression and finishing function.
- Creating objects in a virtual machine is not a thread-safe behavior. It may occur when object A is allocated memory and the pointer has not had time to be modified, and object B uses the original pointer to allocate memory. There are two solutions:
- (1): Synchronize the action of allocating memory space. In fact, the virtual machine uses CAS with failure retry to ensure the atomicity of the update operation;
- (2): The memory allocation action is divided into different spaces according to threads, that is, each thread pre-allocates a small piece of memory in the Java heap, called the local thread allocation buffer (Thread Loal Allocation Buffer, TLAB) .
- After the memory allocation is completed, the allocated memory space needs to be initialized to zero values ??to ensure that the instance fields of the object can be used directly in the Java code without assigning initial values, and the program can access these fields. The zero value corresponding to the data type.
- Set the object, store which class the object is an instance of, how to find the metadata information of the class, the hash code of the object, the GC generation age of the object, etc. in the object header.
2. Memory layout of objects: The layout of objects stored in memory can be divided into three parts: object header (Header), instance data (Instance Data), and alignment padding (Padding). The object header includes two parts of information:
(1): Stores the runtime data of the object itself, such as hash code, GC generation age, lock status flag, lock held by the thread, and bias Thread ID, bias timestamp, etc. The length of this part of data is 32bit and 64bit in 32-bit and 64-bit virtual machines respectively. It is officially called Mark Word (a non-fixed data structure that multiplexes its own storage according to the state of the object). space).
#(2): Type pointer, that is, a pointer to the class metadata of the object. The virtual machine uses this pointer to determine which class the object is an instance of.
- Instance data: The effective information actually stored by the object, that is, the contents of various types of fields defined in the program code. Whether it is inherited from the parent class or defined by the subclass itself, it needs to be recorded.
- Alignment padding: It does not necessarily exist and serves as a placeholder. Since HotSpot VM requires that the size of the object must be an integer multiple of 8 bytes, and the object header part is exactly an integer multiple of 8 bytes, Therefore, when the instance data is not aligned, it is completed by alignment padding.
3. Object access positioning: Java operates specific objects on the heap through reference data on the stack (object references in local variable tables). Reference only specifies references to objects, not Define how to locate and access the location of objects in the heap. The object access method is implemented by Swift.
(1): Handle access: The Java heap will divide a piece of memory as a handle pool. The reference stores the handle address of the object. The handle contains the address information of the object instance data and type data.
Advantages: The reference stores a stable handle address. When the object moves, only the instance data pointer in the handle changes, not the reference.
(2): Direct pointer: What is stored in the reference is directly the object address, and the address of the accessed object type data (stored in the method area) is placed in the Java heap.
Advantages: Faster, saving the time overhead of pointer positioning. HotSpot uses direct pointer access.
The above is the detailed content of Detailed explanation of JVM object creation and access positioning process. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
