当前位置:网站首页>JVM interview
JVM interview
2022-06-09 04:15:00 【Future shadow】
List of articles
Basic concepts :JVM Can be run Java Hypothetical computer of code , Includes a set of bytecode instructions , A set of registers 、 A stack 、 A garbage collection 、 Heap and a storage method domain .JVM Running on the operating system , No direct interaction with hardware
Operation process :java Source files are generated by the compiler Class file ( Bytecode file ), Bytecode file passes again Java The interpreter in the virtual machine is compiled into machine code on a specific machine
- ① Java Source file -> compiler -> Bytecode file
- ② Bytecode file -> JVM -> Machine code
The interpreter of each platform is different , But the virtual machines implemented are the same , That's why JAVA The reasons for being able to cross platform . When a program starts running , At this point, the virtual machine starts to instantiate , There will be multiple virtual machine instances when multiple programs are started . Program exit or close , Then the virtual machine instance dies , Data cannot be shared among multiple virtual machine instances

Threads
The thread here refers to a thread entity in the process of program execution .JVM Allow an application not to execute multiple threads .Hotspot JVM Medium Java There is a direct mapping relationship between threads and native operating system threads . When threads store locally 、 Buffer allocation 、 Synchronize objects 、 Stack 、 When the program counter is ready , It creates an operating system native thread .Java Thread end , Native threads are then recycled , The operating system is responsible for scheduling all threads , And assign them to whatever is available CPU On . When the native thread is initialized , Will call Java Thread run() Method . When the thread ends , Will release native threads and Java All the resources of the thread
Hotspot JVM Background running system threads mainly have the following :
- Virtual machine threads (VM thread): The thread waits JVM The safe point operation appears . These operations have to be performed in separate threads , Because heap modification cannot be performed , Thread needs JVM In a safe place . The types of these operations are :stop-the-world Garbage collection 、 Thread stack dump、 Thread pause 、 Thread bias lock (biased locking) relieve
- Periodic task threads : This thread is responsible for timer events ( interrupt ), Used to schedule the execution of periodic operations
- GC Threads : This thread supports JVM Different garbage collection activities in
- Compiler threads : This thread dynamically compiles bytecode into local platform related machine code at runtime
- Signal distribution thread : This thread receives messages sent to JVM And call the appropriate JVM Method treatment
JVM Memory area

Java The memory area is mainly divided into threads Private areas ( Program counter 、 Virtual machine stack 、 Local method area )、 Threads Shared areas (Java Pile up 、 Method area )、 Direct memory
- The life cycle of thread private data area is the same as thread , Depends on the start of user threads / end and establish / The destruction ( stay Hotspot VM Inside ), Each thread is mapped directly to the local thread of the operating system , So this part of the memory area is stored / Whether to follow the birth of the local thread / Dead correspondence
- The thread sharing area follows the startup of the virtual machine / close and establish / The destruction
- Direct memory is not JVM Part of the runtime data area , But it will also be used frequently : stay JDK1.4 Introduced NIO Provides the basis for Channel And Buffer Of IO The way . It can be used Native Function library directly allocates out of heap memory , And then use DirectByteBuffer Object operates as a reference to this memory ( See :Java I/o Expand ), In this way, we can avoid being in java Heaps and Native Assign data back and forth in the heap , So in some scenarios you can significantly improve performance

Program counter
Thread private , A small block of memory , Is the action indicator of bytecode executed by the current thread
Being implemented java Method words , The counter records the address of the virtual machine bytecode instruction ( The address of the current instruction ), If still Native Method , Is empty
This memory area is the only one not specified in the virtual machine OutOfMemoryError Area of situation
Virtual machine stack
Thread private , describe java Memory model for method execution , Each method creates a stack frame as it executes (Stack Frame) Used to store local variables 、 The stack of operands 、 Dynamic links 、 Method exit information . The process from calling to execution of each method , All correspond to the process of a stack frame from entering the stack to leaving the stack in the virtual machine stack
Stack frame is a data structure used to store data and some process results , It is also used for dynamic link (Dynamic Linking)、 Method return value and exception assignment (Dispatch Exception). Stack frames are created with method calls , Destroy as the method ends —— Whether the method completes normally or abnormally ( Thrown an exception that was not caught within the method ) It's the end of the method

Local method area
Thread private , Local method areas and Java Stack Works in a similar way , The difference is that the virtual machine stack is for execution Java Method service , And the local method stack is Native Method service , If one VM Implementations use C-linkage Model to support Native call , Then the stack will be a C Stack , but HotSpot VM Directly combine the local method stack and virtual machine stack into one
Pile up
Thread sharing , The created objects and arrays are saved in Java In heap memory , It is also the most important memory area of garbage collector for garbage collection , Because of modern VM Using generational collection algorithm , therefore Java Heap from GC The angle can also be subdivided into : The new generation (Eden District 、From Survivor District 、To Survivor District )、 Forever
Method area
Thread sharing , We often say the permanent generation (Permanent Generation), Used to store being JVM Class information loaded 、 Constant 、 Static variables 、 Real time compiler compiled code and other data .HotSpot VM hold GC Generational collection extends to the method area , That is to use Java The permanent generation of the heap implements the method area , such HotSpot The garbage collector can be like management Java Manage this part of memory as a heap , Instead of developing a dedicated memory manager for the method area ( The main goal of permanent generation memory recycling is to recycle the constant pool and unload the type )
Runtime constant pool (Runtime Constant Pool) Is part of the method area ,Class Except for the version of the class in the file 、 Field 、 Method 、 Interface and other description information , There is also an information pool (Constant Pool Table), It is used to store various literal and symbol references generated by the compiler , This part will be stored in the runtime constant pool of the method area after the class is loaded .Java Virtual machines are right Class The format of each part of the document is strictly regulated , Each byte used to store what kind of data must meet the requirements of the specification , This will be recognized by the virtual machine , Load and execute
JVM Run time memory
Java Heap from GC The angle can also be subdivided into : The new generation (Eden District 、From Survivor District 、To Survivor)、 Old age

The new generation
Used to store new objects , Usually occupy the pile 1/3 Space , Because objects are created frequently , So the new generation will happen frequently Minor GC Garbage collection . The Cenozoic is subdivided into Eden District 、Servivor From、Servivor To Three districts
- Eden District :Java The birthplace of the new object ( If the newly created object takes up a lot of memory , It's directly distributed to the old age ), When Eden When there is not enough memory in the area, it will trigger Minor GC, Conduct a garbage collection in the New Area
- Servivor From: Last time GC Survivors of , As this time GC Of those scanned
- Servivor To: Keep it for once MinorGC Survivors in the process
Minor GC The process of ( Copy -> Empty -> swap )
- 1、Eden、Servivor From Copied to the Servivor To, Age +1
- 2、 Empty Eden、Servivor From
- 3、Servivor To And Servivor From swap
Old age
It mainly stores long-lived memory objects in the application program
In the old days, it was relatively stable ,Major GC Not frequently . It's going on Major The first half was done first Minor GC, So that the new generation of objects can be promoted to the old generation , It will be triggered when there is not enough space , When you cannot find enough contiguous space to allocate to the newly created large object, it will also trigger one time in advance Major GC Make room for garbage collection
Major GC Adopt mark clearing algorithm : First scan all the older generation , Mark the living objects , Then recycle unmarked objects ,Major GC It takes a long time , Because to scan and recycle ,Major GC Memory fragmentation will occur , To reduce memory loss , We usually need to merge or mark it for the next direct allocation , When the old age is too full to carry on , Will throw OOM(Out of Memory) abnormal
Forever
The persistent area of memory , Main storage Class and Meta( Metadata ) Information about ,Class It is put into the permanent area when it is loaded , It's different from the area where instances are stored ,GC The permanent area will not be cleaned during the main program operation period , So this also causes the permanent generation region to load as well Class Swell and increase , Finally throw out OOM abnormal
stay Java8 total , Permanent generation removed , One is called “ Metadata area ” Replace the area of . The essence of meta space is similar to permanent generation , The biggest difference between Metaspace and permanent generation is : The meta space is not in the virtual machine , It's using local memory . therefore , By default , The size of the meta space is limited only by local memory , The metadata of the class is put into native memory, String pool and class static variables are put into java In the pile , In this way, the metadata of how many classes can be loaded is no longer controlled by MaxPermSize control , It is controlled by the actual available space of the system
Garbage collection and algorithm

How to determine garbage
- Reference counting : stay Java in , References are related to objects , If you want to manipulate objects, you must reference . therefore , Obviously, a simple way is to use the reference counting method to determine whether an object can be recycled . If an object does not have any references associated with it , That is, the reference count is 0, It means that the object is unlikely to be used again , Then this object is recyclable
- Accessibility analysis : In order to solve the circular reference problem of reference counting method ,Java Accessibility analysis method is used , Through a series of “GC roots” Object search as a starting point , If in GC roots There is no reachable path between and an object , The object is said to be unreachable . Be careful : It takes at least two marking processes for an unreachable object to become a recyclable object , After two tags, it is still a recyclable object , Will face recycling
Tag clearing algorithm
Mark-Sweep, The most basic garbage collection algorithm , There are two stages : mark 、 eliminate . The marking phase records all objects that need to be recycled , The purge phase reclaims the space occupied by the marked objects

The biggest problem of this algorithm is : Memory fragmentation is serious , Subsequently, large objects may not be able to find and use space
Copy algorithm
Copying, In order to solve Mark-Sweep Algorithm memory fragmentation defects of the proposed algorithm . Divide the memory into two equal sized blocks according to the memory capacity , Use only one piece at a time . When this block of memory is full, assign the surviving objects to another block , Clear out used memory

The algorithm is simple to implement , High memory efficiency , It is not easy to produce fragments , But the biggest problem is that the available memory is compressed to half of its original size , And if there are more survivors ,Copying The efficiency of the algorithm will be greatly reduced
Marking algorithm
Mark-Compact, combination mark-Sweep and Copying The defects of . After marking, move the living object to a section of memory , Then clear the objects outside the boundary

Generational collection algorithm
Generational collection algorithms are by far the majority JVM The method adopted , Its core idea is to divide the memory into different regions according to the different life cycles of the objects , In general, it will GC Heaps are divided into new and old generations
New generation and replication algorithms
At present, most of them JVM Of GC For the new generation Copying Algorithm , Because in the new generation, most objects are recycled every time they are recycled , There are fewer operations to copy . The Cenozoic is generally divided into a larger Eden Space and two smaller Survivor Space (From,To), Each use Eden Space and one of them Survivor Space , When it comes to recycling , Copy objects that are still alive in two spaces to another Survivor In the space

Old age and marking algorithm
In the old days, because only a small number of objects were recycled at a time , So we use Mark-Compact Algorithm
summary
- 1、Java The immortal generation in the method area mentioned by the virtual machine (Permanet Generation), It's used to store class class , Constant 、 Method description, etc. , The recovery of immortality mainly includes waste constants and useless classes
- 2、 Object memory allocation is mainly in the new generation Eden Space and Survivor Space Of From Space(Survivor Objective The piece where the object is stored before ), A few cases will be allocated directly to the old generation
- 3、 When the new generation Eden Space and From Space It happens once when there's not enough space GC, Conduct GC after ,Eden Space and From Space Live objects in zone will be moved to To Space, And then Eden Space and From Space Clean up
- 4、 If To Space Not enough to store an object , Then store this object to the old generation
- 5、 It's going on GC after , What we use is Eden Space and To Space 了 , So repeatedly
- 6、 The object is Survivor Avoid the area once GC after , Their age will be + 1, By default, the age is 15 The object will be moved to the old generation
Memory overflow and memory leak
out of memory
- Java The heap memory setting of the virtual machine is not enough
- A large number of large objects are created in the code , And can't be collected by garbage collector for a long time ( There are references )
- stay OOM Before , The garbage collector will be triggered , Collect as much space as possible
- Reference mechanism analysis ,JVM Go back and try to recycle the object pointed to by the soft reference
- java.nio.Bits.reserveMemory() In the method ,System.gc() Will be called
Memory leak
Concept : Object will not be used by the program , however GC You can't recycle them
give an example
- The singleton pattern : The life cycle of a singleton is as long as that of the application , So in the singleton program , If you hold an external reference to an object , Then this external object cannot be recycled , It will lead to memory leakage
- Provide close Your resource is not closed : Database connection 、 network connections 、IO The connection must be manual close, Otherwise, it cannot be recycled
JAVA Four types of references
- Strong citation :Java The most common reference in , Assign an object to a reference variable , When an object is referenced by a strong reference variable , It's reachable , It is impossible for him to be recycled by the garbage collection mechanism , Even if the object will never be used ,JVM It won't recycle , It's the cause of Java One of the main causes of memory leaks
- Soft citation : need SoftReference Class to achieve , For objects with only soft references , It will not be reclaimed when the system memory is sufficient , When the system memory space is insufficient, it will be recycled , Soft references are often used in memory sensitive programs
- Weak reference : need WeakReference Class to achieve , Shorter lifetime than soft references , For objects with only weak references , As soon as the garbage collection mechanism works , No matter JVM Is there enough memory space for , Will reclaim the memory occupied by the object
- Virtual reference : need PhantomReference Class to achieve , Not to be used alone , Must be used in conjunction with the reference queue . The main function of virtual reference is to track the garbage collection status of objects
| type | Recycling time | Use scenarios |
|---|---|---|
| strong | Always alive , Unless GC Roots Unreachable | Scenes of all programs , The basic object , Custom objects, etc . |
| soft | When there is not enough memory, it will be recycled | It is generally used on resources that are very memory sensitive , There are many scenes used as cache , for example : Web caching 、 Image caching |
| weak | Can only survive until the next time GC front | Objects with a short life cycle , for example ThreadLocal Medium Key. |
| virtual | Will be recycled at any time , Once created, it may be recycled soon | There is no use scenario in the industry , May be JVM Used within the team to track JVM Garbage collection activities |
GC Generational collection algorithm VS Partition collection algorithm
Generational collection algorithm
The current mainstream VM Garbage collection adopts generational collection algorithm , This algorithm will divide the memory into several blocks according to the life cycle of the object , Such as JVM The new generation of middle school 、 Old age 、 Forever . In this way, the most appropriate GC Algorithm
- The new generation - Copy algorithm : Every time garbage collection can find a large number of objects are dead , Only a few survive , So choose the replication algorithm , The collection can be completed with a small amount of replication cost of living objects
- Old age - Marking algorithm : The survival rate is high , There is no additional space to guarantee its distribution , You have to use a marker - Organize algorithms to recycle ,
Partition collection algorithm
The partition algorithm divides the whole heap space into consecutive different cells , Each cell is used independently , Independent recycling , The advantage of this is that you can control how many cells are recycled at a time , According to the target pause time , Recycle several cells at a time , So as to reduce one time GC The resulting pause
GC Garbage collector
Java Heap memory is divided into two parts: the new generation and the old generation , The new generation mainly uses replication algorithm ; The old generation is mainly a label sorting algorithm , therefore Java There are many different garbage collectors for the new generation and the old generation in the virtual environment ,JDK1.6 in Sun HotSpot The garbage collector for the virtual machine is as follows :

Serial Garbage collector
Single thread 、 Copy algorithm . Used to be JDK1.3.1 The only garbage collector of the previous generation .Serial It's a single threaded collector , It will not only use one CPU Or a thread to complete garbage collection , And at the same time of garbage collection , All other worker threads must be suspended , Until the end of garbage collection .
Serial A simple and efficient , For a limited single CPU In terms of environment , There is no overhead of thread interaction , Can get the highest single thread garbage collection efficiency , therefore Serial The garbage collector is still java The virtual machine is running in Client The default new generation garbage collector in mode
ParNew Garbage collector
Serial Multithreaded version of . In addition to using multithreading for garbage collection , The rest of the actions and Serial The collector already has ,ParNew The garbage collector also pauses all other worker threads during garbage collection
ParNew The collector is on by default and CPU The same number of threads , It can be done by -XX:ParallelGCThreads Parameter to limit the number of garbage collected threads
ParNew There are many garbage collectors java The virtual machine is running in Server New generation default garbage collector in mode
Parallel Scavenge The collector
A new generation of garbage collectors , Multithreaded replication . It focuses on programs that achieve a Controllable throughput (Thoughput,CPU Time to run user code /CPU Total time consumed , throughput = Run user code time /( Run user code time + Garbage collection time )), High throughput makes the most efficient use of CPU Time , Finish the operation task of the program as soon as possible , It is mainly applicable to tasks that are operated in the background without too much interaction , Adaptive adjustment strategy It's also ParallelScavenge Collector and ParNew An important difference in collectors
Serial Old The collector
Serial Old generation version of garbage collector , Single thread 、 Mark - Arrangement Algorithm . Is running on the Clint Of java The default older generation garbage collector for virtual machines
stay Server In mode , There are two main uses :
- 1、 As JDK1.5 In the previous version and the new generation of Parallel Scavenge Collector used with
- 2、 As an older generation CMS The backup garbage collection scheme of the collector
The new generation Serial With the old generation Serial Old With the garbage collection process diagram

The new generation Parallel Scavenge/ParNew With the old generation Serial Old With the garbage collection process

Parallel Old The collector
Parallel Scavenge Old generation version of , Use The mark of multithreading - Arrangement Algorithm , stay JDK1.6 To start offering
Parallel Old It's to provide throughput first garbage collectors in the elderly as well , If the system requires high throughput , Priority can be given to the new generation Parallel Scavenge And the old generation Parallel Old Collector matching strategy
The new generation Parallel Scavenge And the old generation Parallel Old Collector with running process

CMS The collector
Concurrent mark sweep(CMS) Collector is a kind of old generation garbage collector , The main target : Get the shortest garbage collection pause time , Use The mark of multithreading - eliminate Algorithm
The shortest garbage collection pause time can improve the user experience for programs with high interaction
CMS The working mechanism is as follows :
- Initial marker : Mark the GC Roots Objects that can be directly related , fast , Pause all worker threads
- Concurrent Tags : Conduct GC Roots Process of tracking , Working with user threads , There is no need to pause the worker thread
- Re label : In order to correct during not marking , The part of the object tag record that changes the tag as the user program continues to run , Pause all worker threads
- It's not clear : eliminate GC Roots Unreachable object , Working with user threads , There is no need to pause the worker thread
Because the time-consuming process is not marking and not clearing , The garbage collection thread can work with the user , So on the whole CMS Collector's memory recovery and user threads are executed concurrently

G1 The collector
Garbage first Garbage collector is the most advanced achievement in the development of garbage collector theory , Compared with CMS The collector ,G1 The two most outstanding improvements to the collector are :
- Based on tags - Sorting algorithm , No memory fragmentation
- Can control pause time very precisely , Without sacrificing throughput , Achieve low pause garbage collection
G1 Collectors avoid garbage collection across the region , It divides heap memory into several independent areas of fixed size , And track these areas The garbage collection progress of , At the same time, maintain a priority list in the background , Each time according to the allowed collection time , Priority to recycle the most garbage . Region division and priority region recovery mechanism , Make sure G1 The collector can get the highest garbage collection in a limited time Set efficiency
JAVA IO

Blocking IO Model
The most traditional one IO Model , That is to say, blocking occurs in the process of reading and writing data , When the user thread issues IO After the request , The kernel will check if the data is ready , If it is not ready, it will wait for the data to be ready , And the user thread will be blocked , User thread hands over CPU. When the data is ready , The kernel will copy the data to the user thread , And return the result to the user thread , The user thread is released block state .
Typical congestion IO The example of the model is :data = socket.read(), If there is no data, continue , It's going to be stuck in read Method
Non blocking IO Model
When a user thread initiates a read After the operation , There is no need to wait , It's about getting an immediate result . If it turns out to be error when , I know the data is not ready yet , It can be sent again read operation . Once the data in the kernel is ready , And received the request from the user thread again , Then it will immediately copy the data to the user thread , Then return
The user thread needs to constantly ask if the kernel data is ready , It's going to take up all the time CPU
while(true){
data = socket.read();
if(data!= error){
Processing data
break;
}
}
Multiplexing IO Model
Currently, more models are used ,Java NIO It's actually multiplexing IO Model . A thread continuously polls multiple socket state , When socket When you really write more events , To really call IO Read and write operations
Multiplexing IO In the model , Only one thread is needed to manage multiple socket, The system does not need to create new processes or threads , And you don't have to maintain these threads and processes , Only when there is really socket When reading and writing events are in progress , Will use IO resources , Greatly reduce the resource occupation
Multiplexing IO Non blocking ratio IO The efficiency of the model is high : Multiplexing IO—— Poll each socket The state is in the kernel , Non blocking IO—— inquiry socket The state passes through the user thread
Be careful : Multiplexing IO The model uses polling to detect whether an event arrives , And corresponding to the arrival events one by one . The corresponding body of a weak event is very large , Then the subsequent events will not be handled , It also affects new event polling
Signal driven IO Model
The user thread initiates a IO Request operation , To the corresponding socket Register a signal function , Then the user thread continues to execute , When the kernel data is ready, a signal will be sent to the user thread , The user thread receives the signal and then calls... In the signal function IO Read and write operations for actual IO Request operation
asynchronous IO Model
The ideal IO Model , When the user thread initiates read After the operation , When you leave, you can start doing other things
From the perspective of kernel , When it receives a asynchronous read after , Will return immediately , explain read The request has been successfully initiated , As a result, no block. Then the kernel waits for the data to be ready , Copy data to user thread , When done together , The kernel sends a signal to the user thread , inform read Operation is completed .
JAVA NIO

NIO There are three core parts :Channel( passageway )、Buffer( Buffer zone )、Selector
NIO And traditional IO The biggest difference between :IO Facing the flow ,NIO Facing the buffer
Tradition IO Operation based on byte stream and character stream ; and NIO be based on Channel and Buffer To operate , Data is always passageway <=> buffer
Selector( Selection area ) Used to listen for multiple channel events ( such as : Connection open , Data arrives )-> A single thread can also listen to multiple data channels

NIO The buffer
Java IO Stream oriented means reading one or more bytes from the stream at a time , Until all bytes are read , They are not cached in any place . Besides , It can't move the data in the stream back and forth . If you need to move the data read from the stream back and forth , You need to cache it to a buffer first .NIO The method of buffering guidance is different . The data is read to a buffer that it processes later , Move back and forth in the buffer if needed . This increases the flexibility of the process . however , You also need to check if the buffer contains all the data you need to process . and , Make sure that when more data is read into the buffer , Don't overwrite unprocessed data in the buffer
NIO The non-blocking
IO The various streams of are blocked . It means , When a thread calls read() or write() when , The thread is blocked , Until some data is read , Or write data completely . The thread can't do anything else during this period . NIO Non blocking mode of , Make a thread send a request to read data from a channel , But it can only get data that is currently available , If there is no data available , You will get nothing . Instead of keeping threads blocked , So until the data becomes readable , The thread can continue to do other things . So is nonblocking writing . A thread requests to write some data to a channel , But you don't have to wait for it to write completely , This thread can do other things at the same time . Threads will usually be non blocking IO Free time for execution on other channels IO operation , So a single thread can now manage multiple input and output channels (channel)
Channel
Channel and IO Medium Stream Almost a grade .Stream It's one way , and Channer It's two-way
NIO Medium Channel The main realization of :
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
Corresponding documents IO、UDP、TCP(Server and Client)
Buffer
buffer , It's actually a container , A continuous array .Channel Provide documentation from 、 Network access to data , However, the data read or written must be through Buffer

The customer service end sends data , Deposit in Buffer, then Buffer The content write channel in , Server through Buffer from Channel Get data in
stay NIO in ,Buffer Is a top-level parent class , abstract class . Commonly used Buffer The subclasses of are :ByteBuffer、IntBuffer、 CharBuffer、 LongBuffer、 DoubleBuffer、FloatBuffer、 ShortBuffer
Selector
Selector It can detect whether there are events on multiple registered channels , If something happens , Then get the event, and then deal with the corresponding response for each event
Is to use a single thread can To manage multiple channels , That is, managing multiple connections . So that only when there is a read-write event in the connection , Will call Function to read and write , It greatly reduces the system overhead , And you don't have to create a thread for each connection , No maintenance Multiple threads , It also avoids the overhead caused by context switching between multiple threads
JVM Class loading mechanism
JVM Class loading is divided into five parts : load 、 verification 、 Get ready 、 analysis 、 initialization

- load : Produce a in memory that represents this class java.lang.Class object , As the data entry of the method area class . It doesn't have to be from Class File acquisition , Can also from ZIP Read from ( Such as jar package 、war package ), It can also be calculated at run time to generate ( A dynamic proxy ), It can also be produced from other files (JSP File conversion )
- verification : Make sure Class The information contained in the byte stream of the file meets the requirements of the current virtual machine , And will not harm the security of virtual machine itself
- Get ready : The memory space used to allocate these variables in the method area
- analysis : The process by which a virtual machine converts a symbolic reference in a constant pool into a direct reference
- Symbol reference : The target of the reference does not have to be loaded into memory , The memory layout of various virtual machines can be different , But they must accept the same symbolic references
- Direct reference : Pointer to the target , Relative offset or a handle that can be indirectly located to the target , If there is a direct quote , The referenced target must already exist in memory
- initialization : The last stage of class loading , Start actually executing the... Defined in the class Java Program code
- The initialization phase is the process of executing class constructor methods . Method is a combination of the compiler's automatic collection of class variable assignment operations and statements in static statement blocks . Virtual opportunity guarantees the execution of sub methods , The method of the parent class has been executed , If there is no static variable assignment or static statement block in a class , Then the compiler can not generate for this class () Method
Note that the following situations do not perform class initialization :
- 1、 Reference the static field of the parent class through the child class , Only the initialization of the parent class will be triggered , Does not trigger subclass initialization
- 2、 Defining an array of objects , Initialization of this class will not be triggered
- 3、 Constants are stored in the constant pool of the calling class during compilation , Essentially, there is no direct reference to a class that defines a constant , The class in which the constant is defined will not be triggered
- 4、 Get by class name Class object , Class initialization will not be triggered
- 5、 adopt Class.forName When loading the specified class , If you specify parameters initialize by false when , It doesn't trigger the initial class Initiation , In fact, this parameter tells the virtual machine , Do you want to initialize the class
- 6、 adopt ClassLoader default loadClass Method , It will not trigger the initialization action
JVM Class loader
The virtual machine design team put the load action in JVM External implementation , So that the application decides how to get the required classes ,JVM Provides 3 A loader
- Start class loader : Responsible for loading JAVA_HOME\lib In the directory , Or through -Xbootclasspath Parameter specifies... In the path , And is recognized by the virtual machine ( Such as rt.jar) Class
- Extend the classloader : Responsible for loading JAVA_HOME\lib\ext In the directory , Or through java.ext.dirs The system variable specifies the class library in the path
- Application class loader : Load user path (classpath) Class library

Parents delegate
When a class receives a class load request , He won't try to load the class himself first , Instead, delegate the request to the parent class to complete , This is true of every level classloader , So all the load requests should be sent to the startup class to load , Only When the parent loader reports that it is unable to complete the request ( The required load... Was not found in its load path Class), The subclass loader will try to load itself
The advantage is : The load is located at rt.jar The class in the package java.lang.Object, No matter which loader loads this class , Finally, it is entrusted to the top-level boot class loader for loading , This ensures that different classloaders end up with the same Object object

OSGI
OSGi(Open Service Gateway Initiative), It's for Java Dynamic model system of , yes Java A series of specifications for dynamic modular systems
- Dynamically changing the structure :OSGI The service platform provides the function of dynamically changing the structure on a variety of network devices without restart . To minimize coupling and make it manageable ,OSGI Technology provides a service-oriented architecture , It enables these components to discover each other dynamically
- Modular programming and hot swap :OSGI To achieve Java The modular programming of program provides basic conditions , be based on OSGI The program can realize module level hot plug function , When the program is updated , You can just disable 、 Re install and then start part of the program , This is a very tempting feature for enterprise application development .OSGi It describes a nice modular development goal , And it defines the services and architectures needed to achieve this goal , meanwhile There are also mature frameworks for implementation support . But not all applications are suitable for OSGi As infrastructure , It's providing powerful Functions simultaneously , It also introduces extra complexity , Because it doesn't follow the parent delegation model of class loading
边栏推荐
- 渲染管线----通俗易懂向面试官介绍
- Lua operator
- Wechat applet: (exception) expected begin_ Object but was string at line 1 column 1 path $solution and analysis process
- HashRouter 和 HistoryRouter的区别和原理
- 基于PyQt5完成的PDF拆分
- How is the little red dot that you can't help but click when you see it on the app realized?
- 【word】錯誤!文檔中沒有指定樣式的文字。 1
- (3) Data binding instructions
- 常用端口记录
- 全国大学生信息安全竞赛(CISCN)-reverse-复现(部分)
猜你喜欢

Golang - - paquet d'exécution simultané

App上看到就忍不住点的小红点是如何实现的?

1264_FreeRTOS任务的初始化以及堆栈初始化处理分析
![[software tools] [tutorials] a useful tool for exporting CSDN blog articles to word](/img/40/556cd8c4868a93d4cc06a4a945475d.png)
[software tools] [tutorials] a useful tool for exporting CSDN blog articles to word

Audio power amplifier circuit (used voice scheme circuit record)

MySQL queries which table in the database has the most fields

golang---各个类型变量的比较运算

Software Test Engineer, to what extent can I get 1W in a month?

测试网站搭建+渗透+审计之第三篇Swagger接口渗透测试

数据库连接问题,换版本后无法获取连接
随机推荐
变量提升和函数提升
opcv图像二值化处理
Gradle 渠道包配置
Common port record
Differences and principles between hashrouter and historyrouter
(6) Events
5、快速(分组)排序
Simple reservation system for C language course design classroom
举例说明tf中LSTMCell的cell、num_unit是什么意思
Golang-- concurrent runtime package
Implementation of horizontal and vertical center of unknown width and height elements
声学工程师应知道的150个声学基础知识(全篇)
[excellent design] opencv based face recognition punch in / sign in / attendance management system (the simplest basic library development, which can be based on raspberry pie)
golang---各个类型变量的比较运算
(8)样式绑定
hisi3559av100,MIPI相机输入接口调试
(3) VGg reproduction
ISCC-2022-reverse-mobile-部分wp
《Attention-ocr-Chinese-Version-mas # ter》代码运行逻辑
Mysql 查询数据库中哪个表的字段个数最多
