当前位置:网站首页>Even liver three all night, jvm77 high frequency interview questions detailed analysis, this?
Even liver three all night, jvm77 high frequency interview questions detailed analysis, this?
2020-11-06 01:39:00 【Procedural ape space】
For the convenience of everyone's memory , Remember to collect and pay attention to , Need to download PDF Please click in the official account 【 Programmer space 】 reply “ Information ” You can get the download method , You can also At the end of the text, wechat scanning QR code pays attention to !
1、java Is there a memory leak in , Please give us a brief description .
Meeting . Memory leaks may occur when you implement a heap mounted data structure yourself .
2、64 position JVM in ,int The length of ?
Java in ,int The length of a type variable is a fixed value , It's not about the platform , All are 32 position . That is to say , stay 32 position and 64 position Of Java In the virtual machine ,int The length of the type is the same .
3、Serial And Parallel GC Differences between ?
Serial And Parallel stay GC It will cause stop-the-world. The main differences between them serial Collector is the default replication collector , perform GC When there's only one thread , and parallel Collector uses multiple GC Thread to execute .
4、32 Bit and 64 Bit JVM,int The length of type variable is majority ?
32 Bit and 64 Bit JVM in ,int The length of type variables is the same , All are 32 Bits or 4 Bytes .
5、Java in WeakReference And SoftReference The difference between ?
although WeakReference And SoftReference It's all good for improvement GC and Efficiency of memory , however WeakReference , Once the last strong reference is lost , Will be GC Recycling , While soft references cannot prevent them from being recycled , But it can be delayed to JVM When there is not enough memory .
6、JVM Options -XX:+UseCompressedOops What's the role ? Why use
When you put your app from 32 Bit JVM Migrate to 64 Bit JVM when , Because the pointer of the object 32 The bit has been increased to 64 position , So heap memory will suddenly increase , Almost doubled . That would be right CPU cache ( Capacity is much smaller than memory ) 's data has an adverse impact . because , Migrate to 64 Bit JVM The main motivation is to specify the maximum heap size , By compressing OOP Can save a certain amount of memory . adopt -XX:+UseCompressedOops Options ,JVM Will use 32 Bit OOP, instead of 64 Bit OOP.
7、 How to pass Java Procedure to judge JVM yes 32 position still 64 position ?
You can check some system properties such as sun.arch.data.model or os.arch To get this information .
8、32 position JVM and 64 position JVM The maximum heap memory of is most ?
Theoretically speaking 32 Bit JVM Heap memory reachable 2^32, namely 4GB, But it's actually much smaller than this . Different operating systems , Such as Windows The system is about 1.5GB,Solaris about 3GB.64 position JVM Allow to specify maximum heap memory , In theory 2^64, This is a very large number , In fact, you can specify the heap memory size to 100GB. There are even JVM, Such as Azul, Heap memory to 1000G It's all possible .
9、JRE、JDK、JVM And JIT What's the difference between ?
JRE representative Java Runtime (Java run-time), Is to run Java Required for reference .JDK representative Java development tool (Java development kit), yes Java Program development tools , Such as Java compiler , It also contains JRE.JVM representative Java virtual machine (Java virtual machine), Its responsibility is to run Java application .JIT For immediate compilation (Just In Time compilation), When the number of code execution exceeds a certain threshold , Will Java Bytecode to local code , Such as , The main hotspot code will be changed to local code , This is conducive to a substantial increase Java Application performance .
10、 explain Java Heap space and GC?
When passed Java Command to start Java Process time , Will allocate memory for it . Part of memory is used to create heap space , When creating objects in a program , To allocate memory from the space .GC yes JVM An internal process , Reclaim memory from invalid objects for future allocation .
11、JVM Memory area
JVM Memory area is mainly divided into thread private area 【 Program counter 、 Virtual machine stack 、 Local method area 】、 Thread sharing area 【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 create / The destruction .
Direct memory is not JVM Part of the runtime data area , But it will also be used frequently : stay JDK 1.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 Copy data back and forth in the heap , So in some scenarios you can significantly improve performance .
12、 Program counter ( Thread private )
A small block of memory , Is the line number indicator of the bytecode being executed by the current thread , Each thread must have a separate program counter , This type of memory is also known as “ Thread private ” Of memory .
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 .
13、 Virtual machine stack ( Thread private )
Is to 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 , It corresponds to a stack frame in the virtual machine stack stack stack to the stack process .
Stack frame ( Frame) It is a data structure used to store data and partial process results , It's also used to deal with dynamic links (Dynamic Linking)、 Method return value and exception dispatch (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 .
14、 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 .
15、 You can guarantee GC Is it implemented ?
You can't , Although you can call System.gc() perhaps Runtime.gc(), But there's no guarantee GC Implementation .
16、 How to get Java Memory used by the program ? Percentage of heap usage ?
Can pass java.lang.Runtime Class to get the remaining memory , Total memory and maximum heap memory . Through these methods, you can also get the percentage of heap usage and the remaining space of heap memory .Runtime.freeMemory() Method returns the number of bytes in the remaining space ,Runtime.totalMemory() Method total memory bytes ,Runtime.maxMemory() Returns the maximum number of bytes in memory .
17、Java What's the difference between middle stack and stack ?
JVM Middle heap and stack belong to different memory areas , Different purposes . Stacks are often used to store method frames and local variables , Objects are always allocated on the heap . Stacks are usually smaller than heaps , It will not be shared among multiple threads , And the pile is covered with JVM All threads of share .
18、 Describe the JVM load class The principle and mechanism of documents
JVM The loading of classes in is done by the class loader (ClassLoader) And its subclasses ,Java The various loaders in are an important Java Runtime system components , It is responsible for finding and loading classes in class files at run time .
because Java Cross platform , Compiled Java The source program is not an executable program , But one or more class files . When Java When a program needs to use a class ,JVM Will ensure that this class has been loaded 、 Connect ( verification 、 Preparation and analysis ) And initialize . Class loading refers to the loading of .class The data in the file is read into memory , Usually create a byte array to read in .class file , Then generate the corresponding Class object .
After loading ,Class The object is not complete yet , So the class at this time is not available . When the class is loaded, it enters the connection phase , This phase includes validation 、 Get ready ( Allocate memory for static variables and set default initial values ) And analysis ( Replace symbol references with direct references ) Three steps . Last JVM Initialize the class , Include :1) If a class has a direct parent and the class has not been initialized , Then initialize the parent class first ;2) If there is an initialization statement in the class , Execute these initialization statements in turn .
Class loading is done by the class loader , Class loaders include : Root loader (BootStrap)、 Extended loader (Extension)、 System loader (System) And user-defined class loaders (java.lang.ClassLoader Subclasses of ).
from Java 2(JDK 1.2) Start , The parent delegation mechanism is adopted in the class loading process (PDM).PDM Better guarantee Java Security of the platform , In this mechanism ,JVM Self contained Bootstrap It's a loader , Other loaders have only one parent loader . Class loading first requests the parent class loader to load , When the parent loader is unable to do anything, it will be loaded by its child loader .JVM No direction Java Program provider pair Bootstrap References to . Here are a few classes
Description of the loader :
(1)Bootstrap: Generally implemented by local code , Responsible for loading JVM Basic core class library (rt.jar);
(2)Extension: from java.ext.dirs Load the class library in the directory specified by the system property , Its parent loader is Bootstrap;
(3)System: Also called application class loader , The parent class is Extension. It is the most widely used classloader . It takes the environment variable classpath Or system properties
java.class.path The specified directory records the class , Is the default parent loader for user-defined loaders .
19、GC What is it? ? Why would there be GC?
GC It's rubbish Garbage collection Collective Meaning , Memory Handle It's made up of Cheng Ren Member Rong Easy to come out of Now The question is place , forget perhaps The wrong inner Save back Close up Lead to Program Or it is Unified Unstable It must be Collapse to Collapse , Java Provide Of GC function Sure automatic monitoring object whether exceed effect Domain from And reach From Move back Adduction Deposited Purpose ,Java Language No, Provide Free allocated memory Show operation Method .Java Program No With a load In the heart Depository The reason is , because The garbage collect The device will automatically Conduct management . want request The garbage collect , can In order to tune Use the Face Method One of :System.gc() or Runtime.getRuntime().gc() , but JVM Sure shielding drops Indicated The garbage Recycling call .
Garbage collection can effectively prevent memory leakage , Effective use of available memory . The garbage collector usually runs as a separate low priority thread , Unpredictable cleaning and recycling of dead or unused objects in the memory heap , Programmers can't call the garbage collector to garbage an object or all objects in real time . stay Java Early stage of birth , Recycling is Java One of the biggest highlights , Because programming on the server side needs to effectively prevent memory leakage , But times have changed , Now Java The garbage collection mechanism has become a criticized East . Mobile intelligent end users usually feel that iOS System ratio Android The system has a better user experience , One of the deep reasons is Android The unpredictability of garbage collection in the system .
20、 Pile up (Heap- Thread sharing ) - Run time data area
Is a memory area shared by threads , The created objects and arrays are stored 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 Area and To Survivor District ) And the older generation .
21、 Method area / Forever ( Thread sharing )
That is, we often say the permanent generation (Permanent Generation), Used to store being JVM Class information loaded 、 Constant 、 Static variables are 、 When the compiler compiles the 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 persistent memory recycling is to recycle the constant pool and unload the type , So the benefits are generally small ) .
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 description and other information , Another piece of information is the constant pool (Constant Pool Table), Used to store various literal quantities and symbol references generated during compilation , 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 Each part of the document ( Naturally, constant pools are also included ) There are strict rules for the format of , 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 .
22、JVM Run time memory
Java Heap from GC The angle can also be subdivided into : The new generation (Eden District 、 From Survivor Area and To Survivor District ) And the older generation .
23、 The new generation
It's for storing new objects . Usually occupy the pile 1/3 Space . Because objects are created frequently , So the new generation will trigger MinorGC Garbage collection . The Cenozoic is subdivided into Eden District 、 ServivorFrom、 ServivorTo 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 MinorGC, A garbage collection for the new generation area .
ServivorFrom
Last time GC Survivors of , As this time GC Of those scanned .
ServivorTo
Keep it for once MinorGC Survivors in the process .
MinorGC The process of ( Copy -> Empty -> swap )
MinorGC Using replication algorithm .
(1) eden、 servicorFrom Copied to the ServicorTo, Age +1
First , hold Eden and ServivorFrom Objects that live in the region are copied to ServicorTo Area ( If there is an object's age and has reached the standard of old age , Then assign it to the old generation area ), At the same time put the age of these objects +1( If ServicorTo If you don't have enough space, put it in the old age area );
(2) Empty eden、 servicorFrom
then , Empty Eden and ServicorFrom Objects in the ;
(3) ServicorTo and ServicorFrom swap
Last , ServicorTo and ServicorFrom swap , primary ServicorTo Be the next time GC At the time of the ServicorFrom District .
24、 Old age
It mainly stores long-lived memory objects in the application program .
Old age objects are more stable , therefore MajorGC Not frequently . It's going on MajorGC It's usually done once before MinorGC, Make a new generation of objects into the old age , Trigger when space is not enough . When you cannot find enough contiguous space to allocate to the newly created large object, it will also trigger one time in advance MajorGC Make room for garbage collection .
MajorGC Adopt mark clearing algorithm : First scan all the older generation , Mark the living objects , Then recycle the unmarked objects .ajorGC It takes a long time , Because to scan and recycle .MajorGC 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 , Will throw OOM(Out of Memory) abnormal .
25、 Forever
A permanent storage area of memory , Main storage Class and Meta( Metadata ) Information about ,Class It is put into the permanent area when it is loaded , It is different from the area where the instance is 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 To swell up with , Finally throw out OOM abnormal .
26、JAVA8 And metadata
stay Java8 in , Permanent generation has been removed , Be called by one “ Metadata area ”( Meta space ) 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 nativememory, String pool and class static variables are put into java In the pile , In this way, how many classes of metadata can be loaded is no longer determined by MaxPermSize control , It is controlled by the actual available space of the system .
27、 Reference counting
stay Java in , References are related to objects . If you want to manipulate an object, you have to do it by reference . therefore , Obviously, a simple way is to judge whether an object can be recycled by reference counting . In short , That is, if an object does not have any reference associated with it , That is to say, their reference count is not 0, The object is unlikely to be used again , So this object is a recyclable object .
28、 Accessibility analysis
In order to solve the circular reference problem of reference counting method , Java The method of reachability analysis 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 . It should be noted that , An unreachable object is not equivalent to a recyclable object , It takes at least two marking processes for an unreachable object to become a recyclable object . It's still recyclable after two tags , Will face recycling .
29、 Tag clearing algorithm ( Mark-Sweep)
The most basic garbage collection algorithm , There are two stages , Mark and clear . Marking stage marks all objects to be recycled , The purge phase reclaims the space occupied by the marked objects . Pictured
From the picture we can see , The biggest problem of this algorithm is the memory fragmentation , The problem that large objects can't find available space may occur later .
30、 Copy algorithm (copying)
In order to solve Mark-Sweep Algorithm memory fragmentation 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, copy the surviving objects to another block , Clear out used memory , Pictured :
This 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 .
31、 Marking algorithm (Mark-Compact)
Combined with the above two algorithms , Put forward to avoid defects . Marking stages and Mark-Sweep Same algorithm , After marking is not a cleaning object , Instead, move the live object to one end of memory . Then clear the objects outside the end boundary . Pictured :
32、 Generational collection algorithm
Generational collection is the majority at present JVM The method adopted , The core idea is to divide the memory into different domains according to the different life cycle of the object , In general, it will GC The heap is divided into the old generation (Tenured/Old Generation) And the new generation (YoungGeneration). The characteristic of the old generation is that only a small number of objects need to be recycled each time , The new generation is characterized by a large amount of garbage to be recycled every time , Therefore, different algorithms can be selected according to different regions .
33、 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 , That is, there are fewer operations to copy , But usually not according to 1:1 To divide the new generation . The Cenozoic is generally divided into a larger Eden Space and two smaller Survivor Space (From Space, To Space), Each use Eden Space and a piece of it Survivor Space , When it comes to recycling , Copy the objects that are still alive in the two spaces to another one Survivor In the space .
34、 Old age and mark copy algorithm
In the old days, because only a small amount of objects are recycled at a time , So we use Mark-Compact Algorithm .
(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 The piece where the object is currently stored ), 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 , EdenSpace and From Space Live objects in zone will be moved to To Space, And then Eden Space and FromSpace 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) When the object is Survivor To avoid once GC after , Their age will be +1. By default, age reaches 15 The object of will be moved to the old generation .
35、JAVA Strong citation
stay Java The most common is the strong quotation , Assign an object to a reference variable , This reference variable is a strong reference . When an object is referenced by a strong reference variable , It's reachable , It can't be recycled by garbage collection mechanism , Even if the object will never be used JVM It won't recycle . So strong citations are the cause of Java One of the main causes of memory leaks .
36、JAVA Soft citation
Soft quotes need to use SoftReference Class to achieve , For objects with only soft references , When the system has enough memory, it will not be recycled , When the system runs out of memory, it is recycled . Soft references are often used in memory sensitive programs .
37、JAVA Weak reference
Weak references need to use WeakReference Class to achieve , It has a shorter lifetime than soft quotes , For objects with only weak references , As soon as the garbage collection mechanism works , No matter JVM Is there enough memory space for , Always reclaim the memory occupied by this object .
38、JAVA Virtual reference
Virtual references require PhantomReference Class to achieve , It can't 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 .
39、 Generational collection algorithm
The current mainstream VM Garbage collection uses ” Generational collection ” (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 ones can be adopted according to the characteristics of different ages GC Algorithm
40、 In 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 , Only a small amount of the cost of replication of living objects can complete the collection
41、 In the old age - Marking algorithm
Because of the high survival rate of objects 、 There is no additional space to guarantee its distribution , You have to use “ Mark — clear ” or “ Mark — Arrangement ” Algorithm to recycle , There's no need to do a memory copy , And free up free memory directly .
42、 Partition collection algorithm
The partition algorithm divides the whole heap space into successive 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 ( Not the whole pile ), So as to reduce one time GC The resulting pause .
43、GC Garbage collector
Java Heap memory is divided into two parts: the new generation and the old generation , The new generation mainly uses reproduction and marking - Clear garbage collection algorithm ; The older generation mainly uses markers - Garbage collection 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 :
44、Serial Garbage collector ( Single thread 、 Copy algorithm )
Serial( English is continuous ) Is the most basic garbage collector , Using the replication 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 Although the garbage collector needs to pause all other working threads during garbage collection , But it's 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 .
45、ParNew Garbage collector (Serial+ Multithreading )
ParNew The garbage collector is actually Serial Multithreaded version of collector , Also use the replication algorithm , In addition to using multithreading for garbage collection , The rest of the actions and Serial The collector is exactly the same , 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 , Can pass -XX:ParallelGCThreads Parameter to limit the number of threads in the garbage collector .【Parallel: parallel 】
ParNew Although in addition to multithreading and Serial Collectors are almost the same , however ParNew There are many garbage collectors java The virtual machine is running in Server New generation default garbage collector in mode .
46、Parallel Scavenge The collector ( Multithreaded replication algorithm 、 Efficient )
Parallel Scavenge Collector is also a new generation of garbage collector , Also use the replication algorithm , It's also a multithreaded garbage collector , It focuses on the program to 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 can be used most efficiently 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 is also ParallelScavenge Collector and ParNew An important difference in collectors .
47、Serial Old The collector ( Single thread mark sorting algorithm )
Serial Old yes Serial Old generation version of garbage collector , It's also a single thread collector , Use the tag - Sorting algorithm , This collector is also mainly running in Client default
java The default older generation garbage collector for virtual machines . stay Server In mode , There are two main uses :
(1) stay JDK1.5 In the previous version and the new generation of Parallel Scavenge Collector used with .
(2) Used 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 Collector and ParNew The collector works like , They're all multithreaded collectors , They all use replication algorithms , All worker threads need to be suspended during garbage collection . The new generation ParallelScavenge/ParNew With the old generation Serial Old With the garbage collection process diagram :
48、Parallel Old The collector ( Multithreaded mark sorting algorithm )
Parallel Old The collector is Parallel Scavenge Old generation version of , Use multithreaded tags - Sorting algorithm , stay JDK1.6 To start offering .
stay JDK1.6 Before , The new generation uses ParallelScavenge Collectors can only be used with older generation Serial Old The collector , It can only guarantee the throughput priority of the new generation , There is no guarantee of overall throughput , 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 run process diagram
49、CMS The collector ( Multithreaded mark clearing algorithm )
Concurrent mark sweep(CMS) Collector is a kind of old generation garbage collector , The main goal is to get the shortest garbage collection pause time , And other older generations use markers - Sorting algorithm is different , It uses multithreaded tags - Clear algorithm . The shortest garbage collection pause time can improve the user experience for programs with high interaction .CMS The working mechanism is more complex than other garbage collectors . The whole process is divided into the following 4 Stages :
Initial marker
Just mark it GC Roots Objects that can be directly related , fast , Still need to 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
To fix during concurrent tagging , The tag record of the part of the object whose tag changes as the user program continues to run , Still need to pause all worker threads .
Concurrent elimination
eliminate GC Roots Unreachable object , Working with user threads , There is no need to pause the worker thread . Due to the most time-consuming concurrent tagging and concurrent cleanup process , The garbage collection thread can now work concurrently with the user , So on the whole CMS Collector's memory recovery and user threads are executed concurrently .CMS Collector working process
50、G1 The collector
Garbage first Garbage collector is the most advanced achievement in the development of garbage collector theory , Compared with the CMS The collector , G1 The two most outstanding improvements to the collector are :
(1) Based on tags - Sorting algorithm , No memory fragmentation .
(2) 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 the progress of garbage collection in these areas , 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 efficiency in a limited time
51、JVM Class loading mechanism
JVM The class loading mechanism is divided into five parts : load , verification , Get ready , analysis , initialization , Let's take a look at these five processes .
load
Loading is a stage in the class loading process , This stage will generate a class in memory java.lang.Class object , As the entry point for all kinds of data in this class . Note that there's not necessarily a Class File acquisition , Here you can go from ZIP Read from the package ( For instance from jar Bao He war Read from the package ), It can also be calculated at run time to generate ( A dynamic proxy ), Can also be generated by other files ( For example, will JSP Convert files to corresponding Class class ).
verification
The main purpose of this stage is to ensure that Class Whether the information contained in the byte stream of the file meets the requirements of the current virtual machine , And will not endanger the security of virtual machine itself .
Get ready
The preparation stage is the stage of formally allocating memory for class variables and setting the initial value of class variables , That is, the memory space used to allocate these variables in the method area . Pay attention to the concept of initial value , For example, a class variable is defined as :
Actually variable v The initial value after the preparation phase is 0 instead of 8080, take v The assignment is 8080 Of put static An instruction is when a program is compiled , Stored in class constructor methods .
But note that if the statement is :
public static final int v = 8080;
During the compilation phase v Generate ConstantValue attribute , In the preparation stage, the virtual opportunity is based on ConstantValue Property will be v The assignment is 8080.
analysis
The parsing phase refers to the process that the virtual machine replaces the symbol reference in the constant pool with the direct reference . A symbolic reference is class In the document
public static int v = 8080;
Actually variable v The initial value after the preparation phase is 0 instead of 8080, take v The assignment is 8080 Of put static An instruction is when a program is compiled , Stored in class constructor methods . But note that if the statement is :
During the compilation phase v Generate ConstantValue attribute , In the preparation stage, the virtual opportunity is based on ConstantValue Property will be v The assignment is 8080.
analysis
The parsing phase refers to the process that the virtual machine replaces the symbol reference in the constant pool with the direct reference . A symbolic reference is class In the document
public static final int v = 8080;
During the compilation phase v Generate ConstantValue attribute , In the preparation stage, the virtual opportunity is based on ConstantValue Property will be v The assignment is 8080.
analysis
The parsing phase refers to the process that the virtual machine replaces the symbol reference in the constant pool with the direct reference . A symbolic reference is class In the document :
(1) CONSTANT_Class_info
(2)CONSTANT_Field_info
(3)CONSTANT_Method_info
Constant of the same type .
Symbol reference
Symbol references are independent of the layout of the virtual machine implementation , The target of the reference does not have to be loaded into memory . The memory layout of various virtual machines can be different , But the symbolic references they can accept must be consistent , Because the literal form of symbolic reference is clearly defined in Java Virtual machine specification Class In file format .
Direct reference
A direct reference can be a pointer to a target , Relative offset or a handle that can be indirectly located to the target . If there is a direct quote , The target of the reference must already exist in memory .
initialization
The initialization phase is the last stage of class loading , After the previous class loading phase , In addition to being able to customize the classloader during the loading phase , Other operations are done by JVM The dominant . At the initial stage , To actually execute what is defined in the class Java Program code .
class constructor
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 the initialization of the subclass .
(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 , Class initialization will not be triggered , 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 .
52、 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 Type loader :
Start class loader (Bootstrap ClassLoader)
Responsible for loading JAVA_HOME\lib In the directory , Or through -Xbootclasspath Parameter specifies... In the path , And is recognized by the virtual machine ( Identify by file name , Such as rt.jar) Class .
Extend the classloader (Extension 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 (Application ClassLoader):
Responsible for loading user paths (classpath) Class library .JVM Load the class through the parent delegation model , Of course, we can also inherit java.lang.ClassLoader Implement custom class loader .
53、 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 cannot complete the request ( The required load... Was not found in its load path Class), The subclass loader will try to load itself .
One of the benefits of using parental delegation is that for example, the load is located in 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
54、OSGI( Dynamic model system )
OSGi(Open Service Gateway Initiative), It's for Java Dynamic model system of , yes Java A series of specifications for dynamic modular systems .
55、 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 .
56、 Modular programming and hot swap
OSGi To achieve Java The modular programming of program provides basic conditions , be based on OSGi It is possible to implement 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 program development .
OSGi It describes a nice modular development goal , And it defines the services and architectures needed to achieve this goal , At the same time, there is a mature framework for implementation support . But not all applications are suitable for OSGi As infrastructure , It provides powerful functions at the same time , It also introduces extra complexity , Because it doesn't follow the parent delegation model of class loading .
57、JVM Memory model
Thread exclusive : Stack , Native Method Stack , Program counter
Thread sharing : Pile up , Method area
58、 Stack
Also called method stack , Thread private , Thread execution method is to create a stack array , Used to store local variable table , Stack operation , Dynamic links , Method exit information . Execute push on method call , Method returns to execute the stack .
59、 Native Method Stack
Similar to stack , It is also used to save the information of the execution method . perform Java The method is to use the stack , perform Native Method using the local method stack .
60、 Program counter
Saves the bytecode location of the current thread execution , Each thread has its own counter when it works , Just for execution Java Method service , perform Native When the method is used , Program counter is empty .
61、 Pile up
JVM The biggest part of memory management , To be shared by threads , The object of an instance is to store the object , Almost all the object instances you want will be placed here , When the heap has no free space , Will throw out OOM abnormal . Depending on the life cycle of the object ,JVM Manage objects by generations , The garbage collector is responsible for garbage collection management
62、 Method area
Also known as non heap area , Used to store class information loaded by virtual machine , Constant , Static variables , Real time compiler optimized code and other data .1.7 Permanent generation and 1.8 The meta space of the method area is an implementation of the method area .
63、 Generational recycling
Generational recycling is based on two facts : Most of the objects are soon out of use , And some of it won't be immediately useless , But it won't last long
The younger generation -> Mark - Copy
Old age -> Mark - eliminate
64、 The difference between heap and stack
A stack is a runtime unit , It stands for logic , Contains basic data types and heap object references , The area is continuous , There are no fragments ; A heap is a unit of storage , Represents data , Can be shared by multiple stacks ( Include basic data types in members 、 References and reference objects ), The area is discontinuous , There will be pieces .
(1) Different functions
Stack memory is used to store local variables and method calls , And heap memory is used to store Java Objects in the . Whether it's a member variable , local variable , Or class variables , The objects they point to are stored in heap memory .
(2) Sharing is different
Stack memory is thread private .
Heap memory is common to all threads .
(3) Abnormal errors are different
If there is not enough stack memory or heap memory, an exception will be thrown .
Not enough stack space :java.lang.StackOverFlowError.
There's not enough heap space :java.lang.OutOfMemoryError.
(4) The size
The size of the stack is much smaller than that of the heap
65、 When will it trigger FullGC
Except for calling directly System.gc Outside , Trigger Full GC There are four types of implementation .
(1) There is not enough space for the old generation
The old generation space is only transferred into and created as large objects in the new generation 、 Large array will be insufficient , When executed Full GC There is still not enough space behind , Then throw the following error
By mistake :
java.lang.OutOfMemoryError: Java heap space
In order to avoid the above two conditions FullGC, When tuning, try to keep objects in Minor GC The stage is recycled 、 Keep objects alive for a long time in the new generation and don't create too large objects and arrays .
(2) Permanet Generation Space is full
PermanetGeneration Some of them are stored in class Information, etc , When the class to be loaded in the system 、 When there are many reflected classes and called methods ,Permanet Generation May be full of , When not configured to use CMS GC In the case of Full GC. If passed Full GC Still can't recycle , that JVM The following error message will be thrown :
java.lang.OutOfMemoryError: PermGen space
To avoid Perm Gen Fill up causes Full GC The phenomenon , The method that can be used is to increase Perm Gen Space or turn to use CMS GC.
(3)CMS GC When promotion failed and concurrent mode failure
To adopt CMS Carry on the old generation GC In terms of procedures , Pay special attention to GC Is there any promotion failed and concurrent mode failure Two conditions , When these two conditions occur, it may trigger Full GC.
promotionfailed It's going on Minor GC when ,survivor space can't let go 、 Objects can only be put into the old generation , At this time, the old generation couldn't let go of the causes ;concurrentmode failure It's execution CMS GC At the same time, there are objects to put into the old generation , At this time, the space of the old generation is insufficient .
The countermeasures are : increase survivorspace、 Old generation space or lower trigger concurrency GC Ratio of , But in JDK 5.0+、6.0+ It may be due to JDK Of bug29 Lead to CMS stay remark It's long after it's over sweeping action . For this situation , By setting -XX:CMSMaxAbortablePrecleanTime=5( Unit is ms) To avoid .
(4) Statistics get Minor GC The average size of promotion to the old generation is larger than the remaining space of the old generation
This is a more complex trigger situation ,Hotspot In order to avoid the phenomenon that the space of the old generation is insufficient due to the promotion of the new generation to the old generation , It's going on Minor GC when , Made a judgment , If the previous statistics show that Minor GC The average size of promotion to the old generation is larger than the remaining space of the old generation , Then trigger it directly Full GC.
For example, the first trigger of the program MinorGC after , Yes 6MB To the old generation , So the next time Minor GC occurs , First, check whether the remaining space of the old generation is greater than 6MB, If it is less than 6MB, execute Full GC.
When the new generation adopts PSGC when , It's a little different ,PS GC Is in Minor GC I'll check it later , For example, for the first time in the above example Minor GC after ,PS GC It will check whether the remaining space of the old generation is greater than 6MB, If less than , It triggers the recycling of the old generation . In addition to the above 4 Out of these conditions , For the use of RMI To carry out RPC Or managed Sun JDK In terms of application , By default, it will be executed once an hour Full GC. Can be passed at startup - java-Dsun.rmi.dgc.client.gcInterval=3600000 To set up Full GC The interval or passage of execution -XX:+ DisableExplicitGC To prohibit RMI call System.gc
66、 What is? Java virtual machine ? Why? Java Be called “ Platform independent programming language ”?
Java Virtual machine is an executable Java Virtual machine process of bytecode .Java Source files are compiled to be able to be Java Bytecode file executed by virtual machine .Java Designed to allow applications to run on any platform , It doesn't need to be rewritten or recompiled by the programmer for each platform .Java Virtual machines make this possible , Because it knows the instruction length and other characteristics of the underlying hardware platform .
67、 Object allocation rules
(1) The priority of objects is Eden District , If Eden When there is not enough space in the area , The virtual machine executes once Minor GC.
(2) Large objects go directly into the old generation ( Large objects are objects that require a large amount of continuous memory space ). The purpose of this is to avoid Eden Area and two Survivor There are a lot of memory copies between regions ( The new generation uses replication algorithms to collect memory ).
(3) Long term survivors enter the old age . The virtual machine defines an age counter for each object , If the object passes by 1 Time Minor GC Then the object will enter Survivor District , Every time after that Minor GC Then the age of the object plus 1, Know that people who reach the threshold enter the elderly area .
(4) Dynamically judge the age of the object . If Survivor The sum of all object sizes of the same age in the area is greater than Survivor Half of the space , Objects older than or equal to this age can enter the elderly generation directly .
(5) Space allocation guarantee . Every time Minor GC when ,JVM Calculation Survivor The average size of objects moved to the elderly area , If this value is larger than the remaining value of the elderly area, it will be done once Full GC, If less than check HandlePromotionFailure Set up , If true Then just go ahead Monitor GC, If false Is to Full GC
68、 Describe the JVM load class The principle and mechanism of documents ?
JVM The loading of classes in is done by the class loader (ClassLoader) And its subclasses ,Java The classloader in is an important Java Runtime system components , It is responsible for finding and loading classes in class files at run time .
because Java Cross platform , Compiled Java The source program is not an executable program , But one or more class files . When Java When a program needs to use a class ,JVM Will ensure that this class has been loaded 、 Connect ( verification 、 Preparation and analysis ) And initialize .
Class loading refers to the loading of .class The data in the file is read into memory , Usually create a byte array to read in .class file , Then generate the corresponding Class object . After loading ,Class The object is not complete yet , So the class at this time is not available .
When the class is loaded, it enters the connection phase , This phase includes validation 、 Get ready ( Allocate memory for static variables and set default initial values ) And analysis ( Replace symbol references with direct references ) Three steps . Last JVM Initialize the class ,
Include :
(1) If a class has a direct parent and the class has not been initialized , Then initialize the parent class first ;
(2) If there is an initialization statement in the class , Execute these initialization statements in turn . Class loading is done by the class loader , Class loaders include : Root loader (BootStrap)、 Extended loader (Extension)、 System loader (System) And user-defined class loaders (java.lang.ClassLoader Subclasses of ).
from Java 2(JDK 1.2) Start , The parent delegation mechanism is adopted in the class loading process (PDM).PDM Better guarantee Java Security of the platform , In this mechanism ,JVM Self contained Bootstrap It's a loader , Other loaders have only one parent loader . Class loading first requests the parent class loader to load , When the parent loader is unable to do anything, it will be loaded by its child loader .JVM No direction Java Program provider pair Bootstrap References to . Here's a description of several classloaders
**Bootstrap:** Generally implemented by local code , Responsible for loading JVM Basic core class library (rt.jar);
**Extension:** from java.ext.dirs Load the class library in the directory specified by the system property , Its parent loader is Bootstrap;
**System:** Also called application class loader , The parent class is Extension. It is the most widely used classloader . It takes the environment variable classpath Or system properties java.class.path The specified directory records the class , Is the default parent loader for user-defined loaders .
69、Java Object creation process
(1)JVM When encountering an instruction of a new object, first check whether the parameter of the instruction can be defined to the symbol reference of a class in the constant pool . Then load the class ( Class loading process will be discussed later )
(2) Allocate memory for objects . One way “ Pointer collision ”、 One way “ Free list ”, The final common method “ Local thread buffer allocation (TLAB)”
(3) Initialize the object memory space other than the object header to 0
(4) Make the necessary settings for the object header
70、 sketch Java Object structure of
Java The object consists of three parts : Object head 、 The instance data 、 Alignment filling .
The object head consists of two parts , The first part stores the runtime data of the object itself : Hash code 、GC Generational age 、 Lock identification status 、 A lock held by a thread 、 To the thread ID( In general 32/64 bit). The second part is pointer type , The type of class metadata pointing to the object ( Which class does the object represent ). If it's an array object , Then there is a part of the object header to record the array length .
Instance data is used to store the real effective information of objects ( Including the inherited and self-defined )
Alignment filling :JVM The starting address of the object is required to be 8 Integer multiples of bytes (8 Byte alignment )
71、 How to judge whether an object can be recycled
There are generally two ways to judge whether an object is alive :
** Reference count :** Each object has a reference count property , Add a reference count plus 1, Count minus when reference is released 1, Count as 0 It can be recycled . This method is simple , Can't solve the problem of circular references between objects .
** Accessibility analysis (Reachability Analysis):** from GC Roots Start looking down , The path a search takes is called a reference chain . When an object arrives GC Roots When no chain of references is connected , Then prove that this object is not available , Unreachable object .
72、JVM Will garbage collection take place in the permanent generation of
Garbage collection will not happen in the permanent generation , If the permutation is full or the critical value is exceeded , Will trigger full garbage collection (Full GC). If you look closely at the output of the garbage collector , It will be found that the permanent generation is also recycled . That's why the right permanent generation size to avoid Full GC It's a very important reason . Please refer to Java8: From permanent generation to metadata area ( notes :Java8 Permanent generation has been removed from , A new one called metadata area has been added native Memory area )
73、 Garbage collection algorithm
GC There are three basic algorithms : Mark - Clear algorithm 、 Copy algorithm 、 Mark - Compression algorithm , Our commonly used garbage collectors generally adopt the generational collection algorithm .
Mark - Clear algorithm
“ Mark - eliminate ”(Mark-Sweep) Algorithm , Like its name , The algorithm is divided into “ Mark ” and “ eliminate ” Two phases : First mark all objects to be recycled , Recycle all marked objects after marking .
Copy algorithm
“ Copy ”(Copying) The collection algorithm of , It divides the available memory into two equal sized blocks according to the capacity , Use only one piece at a time . When this block of memory runs out , Copy the living object to another piece , Then clean up the used memory space at a time .
Mark - Compression algorithm
The marking process is still associated with “ Mark - eliminate ” Algorithm is the same , But the next step is not to clean up the recyclable objects directly , I'm going to move all the living objects towards one end , Then directly clean up the memory outside the end boundary
Generational collection algorithm
“ Generational collection ”(Generational Collection) Algorithm , hold Java The heap is divided into the new generation and the old generation , In this way, the most appropriate collection algorithm can be adopted according to the characteristics of each era
74、 What are the tuning commands ?
Sun JDK Monitoring and troubleshooting commands are jps jstat jmap jhat jstack jinfo
(1)jps,JVM Process Status Tool, Display all... In the specified system HotSpot Virtual machine process .
(1)jstat,JVM statistics Monitoring Is a command used to monitor virtual machine runtime state information , It can show class loading in the virtual machine process 、 Memory 、 garbage collection 、JIT Compile and other operation data .
(3)jmap,JVM Memory Map The command is used to generate heap dump file
(4) jhat,JVM Heap Analysis Tool The order is with jmap Use it with , Used for analysis jmap Generated dump,jhat Built in a micro HTTP/HTML The server , Generate dump After analyzing the results of , You can view... In a browser
(5)jstack, Used to generate java A snapshot of the thread at the current moment in the virtual machine .
(6) jinfo,JVM Configuration info The function of this command is to view and adjust the running parameters of virtual machine in real time
75、 Tuning Tools
Common tuning tools are divided into two categories ,jdk Bring your own monitoring tools :jconsole and jvisualvm, The third party has :MAT(Memory AnalyzerTool)、GChisto.
(1) jconsole,Java Monitoring and Management Console It's from java5 Start , stay JDK The built-in java Monitoring and management console , Used to deal with JVM Medium memory , Thread and class monitoring
(2)jvisualvm,jdk Bring your own all-around tools , Can analyze memory snapshot 、 Thread snapshot ; Monitor memory changes 、GC Change, etc .
(3)MAT,Memory Analyzer Tool, One is based on Eclipse Memory analysis tools , It's a fast one 、 functional Javaheap Analysis tools , It can help us find memory leaks and reduce memory consumption
(4)GChisto, A professional analysis gc Logging tools
76、Minor GC And Full GC When do they happen ?
New generation memory shortage occurs MGC Also called YGC,JVM Occurs when there is not enough memory FGC
77、 You know what JVM performance tuning
Set heap memory size
-Xmx: Maximum heap memory limit .
Set the size of the new generation . The new generation should not be too small , Otherwise, a large number of objects will flow into the elderly generation
-XX:NewSize: The size of the new generation
-XX:NewRatio The proportion of new generation and old generation
-XX:SurvivorRatio: Proportion of Eden space and survivor space
Set up a garbage collector Young substitute -XX:+UseParNewGC Old age substitute -XX:+UseConcMarkSweepGC
版权声明
本文为[Procedural ape space]所创,转载请带上原文链接,感谢
边栏推荐
- 这个项目可以让你在几分钟快速了解某个编程语言
- Linked blocking Queue Analysis of blocking queue
- 新建一个空文件占用多少磁盘空间?
- 每个大火的“线上狼人杀”平台,都离不开这个新功能
- How to encapsulate distributed locks more elegantly
- Jmeter——ForEach Controller&Loop Controller
- 6.6.1 localeresolver internationalization parser (1) (in-depth analysis of SSM and project practice)
- 每个前端工程师都应该懂的前端性能优化总结:
- For a while, a dynamic thread pool was created, and the source code was put into GitHub
- What is the side effect free method? How to name it? - Mario
猜你喜欢
Building and visualizing decision tree with Python
(1) ASP.NET Introduction to core3.1 Ocelot
理解格式化原理
Custom function form of pychar shortcut key
Summary of common algorithms of linked list
Individual annual work summary and 2019 work plan (Internet)
Python filtering sensitive word records
vue任意关系组件通信与跨组件监听状态 vue-communication
It's so embarrassing, fans broke ten thousand, used for a year!
01. SSH Remote terminal and websocket of go language
随机推荐
Common algorithm interview has been out! Machine learning algorithm interview - KDnuggets
How to demote domain controllers and later in Windows Server 2012
带你学习ES5中新增的方法
Electron application uses electronic builder and electronic updater to realize automatic update
Vue.js Mobile end left slide delete component
C + + and C + + programmers are about to be eliminated from the market
Summary of common algorithms of linked list
How to use parameters in ES6
Analysis of query intention recognition
How to encapsulate distributed locks more elegantly
Our best practices for writing react components
Summary of common algorithms of binary tree
use Asponse.Words Working with word templates
Simple summary of front end modularization
【自学unity2d传奇游戏开发】地图编辑器
Python filtering sensitive word records
一篇文章带你了解CSS3图片边框
The data of pandas was scrambled and the training machine and testing machine set were selected
vue任意关系组件通信与跨组件监听状态 vue-communication
How to get started with new HTML5 (2)