Java virtual machine (JVM) yes Java The running environment of the application , In a general sense ,JVM It's a virtual computer defined by a specification , Designed to explain the execution from Java Bytecode compiled from source code . More colloquially ,JVM It refers to the concrete implementation of this specification . This implementation is based on a strict instruction set and a comprehensive memory model . in addition ,JVM It is also often described as the implementation of the software runtime environment . Usually JVM Realization mainly refers to HotSpot.

JVM The specification guarantees that any implementation can interpret the execution bytecode in the same way . Its implementation can be diversified , Including process 、 independent Java Operating system or processor chip that directly executes bytecode . What we know the most about JVM It's implemented as software , Running on popular operating system platforms ( Include Windows、OS X、Linux and Solaris etc. ).

JVM The structure of allows for a Java Application for more subtle control . These apps run in sandbox (Sandbox) Environment . Make sure that without proper permission , Unable to access local file system 、 Processor and network connection . When executing remotely , The code also needs to be certified .

In addition to interpretation and execution Java Bytecode , Most of the JVM The implementation also includes a JIT(just-in-time instant ) compiler , Used to generate machine code for commonly used methods . The machine code uses CPU The local language of , It's faster than bytecode .

Although understand JVM Not to develop or run Java The necessary conditions of procedure , But if you know more JVM knowledge , So there's a chance to avoid a lot of performance problems . I understand JVM, In fact, these questions will become simple and clear .

Architecture

JVM The specification defines a set of subsystems and their external behaviors .JVM There are mainly the following subsystems :

  • Class Loader  Class loader . Used to read in Java Source code and load the class into the data area .
  • Execution Engine  Execution engine . Execute instructions from the data area .

The data area uses the underlying operating system assigned to JVM Of memory .

Class loader (Class Loader)

JVM Use different class loaders at different levels :

  • bootstrap class loader( Boot class loader ): Is the parent of other class loaders , It's used to load Java Core library , And it's the only class loader written in native code .
  • extension class loader( Extend the classloader ): yes bootstrap class loader Subclasses of loaders , Used to load extension Libraries .
  • system class loader( system class loader ): yes extension class loader Subclasses of loaders , For loading in classpath Class files for applications in .
  • user-defined class loader( User defined class loader ): Is a subclass of a system class loader or other user-defined class loader .

When a class loader receives a request to load a class , First, it checks the cache , Confirm whether the class has been loaded , Then proxy the request to its parent class . If the parent class fails to load the class , Then the subclass will try to load the class itself . Subclasses can check the cache of the parent loader , But the parent class can't see the class loaded by the child class . The loading system is designed like this , It is considered that a subclass should not repeatedly load a class that has been loaded by the parent class .

Execution engine (Execution Engine)

The execution engine executes the bytecode loaded into the data area one by one . To ensure that bytecode instructions are machine readable , The execution engine uses the following two methods :

  • Explain to perform : The execution engine interprets every instruction it encounters as machine language .
  • Just in time compilation : If an instruction is often used , The execution engine compiles it into native code and stores it in the cache . such , All code associated with this method is executed directly , So as to avoid repeated explanation .

Although just in time compilation takes more time than interpretation execution , But for methods that need to be used thousands of times , It only needs to be dealt with once . Instead of explaining and executing every time , Running in native code saves a lot of execution time .

JVM The specification does not require immediate compilation . Just in time compilation is not meant to improve JVM The only means of performance . The specification only specifies the local code for each bytecode , As for how the execution engine implements this corresponding process , Completely by JVM The concrete realization of .

Memory model (Memory Model)

Java The memory model is built on the concept of automatic memory management . When an object is no longer referenced by an application , The garbage collector will recycle it , So as to release the corresponding memory . This is very different from many other languages that need to free memory on their own .

JVM Allocating memory from the underlying operating system , And divide them into the following areas :

  • Heap space (Heap Space): This is the shared memory area , Used to store objects that can be recycled by the garbage collector .
  • Method area (Method Area): This area used to be called “ Eternal generation ”(permanent generation), Used to store loaded classes . This area has recently been JVM To cancel the . Now? , The loaded class is loaded as metadata into the local memory area of the underlying operating system .
  • The region (Native Area): This area is used to store references and variables of basic types .

An effective way to manage memory is to divide the space into different generations , So the garbage collector doesn't have to scan the entire heap . Most objects have a short life cycle , Objects with a long life cycle often do not need to be cleared until the application exits .

When one Java The application creates an object , This object is stored in “ Newborn pool ”(eden pool). Once the newborn pool is full , It will trigger once in the new generation minor gc( Small scale recycling ). First , The garbage collector will mark those “ Dead man ”( Objects that are no longer referenced by the application ), Extend the life cycle of all retained objects at the same time ( The length of this life cycle is described in numbers , Represents the number of garbage collections that have been experienced during the period ). then , The garbage collector will collect these dead objects , And move the remaining living objects to “ Survival pool ”(survivor pool), To clear the birth pool .

When an object survives for a certain period of time , It will be moved to the old generation in the heap :“ Lifelong generation ”(tenured pool). Last , When lifetimes are filled , It will trigger once full gc or major gc( Complete garbage collection ), To clean up generations of .

( translator's note : Generally, we combine the areas where the primary pool and the surviving pool are located to form the Cenozoic , Make the area where the lifelong generation is located the old generation . Corresponding , In the new generation gc be called minor gc, Born in the old generation gc be called full gc. I hope you can understand the corresponding terms better when you see them in other places )

When garbage collection (gc) When it comes to execution , All application threads have to be stopped , The system generates a pause .minor gc Very often , So the optimized one can quickly recycle dead objects , It's the main way to recycle the memory of the new generation .major gc It's much slower to run , Because we have to scan a lot of living objects . There are many implementations of the garbage collector itself , Some garbage collectors can perform faster under certain circumstances major gc.

The size of the heap is dynamic , Only when the heap needs to expand will it be allocated from memory . When the pile is full ,JVM Will reallocate more memory to the heap , Until you reach the maximum heap size , This redistribution can also lead to a temporary stop of the application .

Threads

JVM It runs in a separate process , But it can execute multiple threads concurrently , Each thread runs its own method , This is a Java A necessary part . Take an application like instant messaging client as an example , It runs at least two threads . A thread is used to wait for user input , The other is to check whether the server has new message transmission . Take the server application as an example , Sometimes a request may involve concurrent execution of multiple threads , So multithreading is needed to process the request .

stay JVM In the process of , All threads share memory and other available resources . every last JVM The process is at the entry point (main Method ) Start a main thread at all times , Other threads start from the main thread , Become an independent part of the execution process . Threads can be executed in parallel on different processors , It's also possible to share a processor , The thread scheduler is responsible for dealing with the situation that multiple threads share a processor .

Many applications ( Especially for server applications ) I can handle a lot of tasks , Need to run in parallel . Some of these tasks are very important , What needs to be executed in real time . And others are backstage tasks , Can be in CPU Execute when idle . Tasks run in different threads . For example , The server may have some low priority threads , They calculate statistics based on some data . At the same time, some high priority processes will be started to process the incoming data , Responding to requests for these statistics . There may be a lot of source data , A lot of data requests from clients , Each request will cause the server to temporarily stop the thread of background computing in response to this request . therefore , You have to monitor the number of threads running and make sure there are enough CPU Time to perform the necessary calculations .

( translator's note : This paragraph is in the chapter of performance optimization in the original text , The translator thinks it may be the author's carelessness , It seems more appropriate to put it in the chapter of thread .)

performance optimization

JVM Its performance depends on whether its configuration matches the function of the application . Although the garbage collector and the memory recovery process manage memory automatically , But you have to control their frequency . Generally speaking , The more memory your app can use , The less memory management processes that cause applications to pause, the less they need to work .

If garbage collection happens more often than you think , Then you can start JVM Configure a larger maximum heap size value for it . The longer the pile is filled , The more likely it is to reduce the frequency of garbage collection . The maximum heap size can be set at startup JVM When , use -Xmx Parameters to set . The default maximum heap size is set to a quarter of the available operating system memory , Or the smallest 1GB.

If the problem is frequent reallocation of memory , Then you can set the initialization heap size to be the same as the maximum heap size . That means JVM Never reallocate memory for the heap . But doing so will lose the optimization of dynamic heap size adaptation , The size of the heap is fixed from the beginning . Configuration initialization pair size is at startup JVM, use -Xms To set . The default initialization heap size will be set to sixty-four times the physical memory available to the operating system , Or set a minimum value . This value is determined according to different platforms .

If you know what kind of garbage collection it is (minor gc or major gc) Causing performance problems , You can set the size ratio of the Cenozoic to the old generation without changing the size of the whole heap . For applications that need to generate a large number of temporary objects , We need to increase the proportion of Cenozoic generation ( Of course , The result is a reduction in the size of the older generation ). For more applications with long life cycle objects , We need to increase the proportion of the old generation ( Nature needs to reduce the size of the Cenozoic ). The following methods can be used to set the size of the Cenozoic and the old generation :

  • Start up JVM when , Use -XX:NewRatio Parameter to specify the size ratio between the Cenozoic and the old generation . such as , If you want the old generation to be five times the size of the new generation , Then set the parameter to -XX:NewRatio=5, By default, this parameter is set to 2( That is, the older generation occupies two-thirds of the heap space , The new generation takes up a third of ).
  • Start up JVM when , Use it directly -Xmn Parameter setting initialization and maximum Cenozoic size , Then the remaining size in the heap is the size of the old generation .
  • Start up JVM when , Use it directly -XX:NewSize and -XX:MaxNewSize Parameter setting initialization and maximum Cenozoic size , Then the remaining size in the heap is the size of the old generation .

Every thread has a stack , Used to save function calls 、 Return address, etc , These stacks have corresponding memory allocation . If there are too many threads , It will lead to OutOfMemory error . Even if you have enough space in the heap to hold objects , Your application may also crash by creating a new thread . In this case , Consider limiting the maximum stack size in a thread . The thread stack size can be in JVM When it starts , adopt -Xss Parameter to set , By default, this value is set to 320KB to 1024KB Between , It's about the platform .

Performance monitoring

When developing or running a Java When applied , Yes JVM It's important to monitor the performance of . To configure JVM It's not all in one configuration , In particular, what you have to deal with is Java Server applications . You have to constantly check the allocation and usage of heap and non heap memory , How many threads are created and how many classes are loaded in memory . These are the core parameters .

Use Anturis Console , You can run it on any hardware component JVM Configure monitoring ( for example , One that runs on a computer Tomcat Web server ).

JVM Monitoring can use the following metrics :

  • Total memory usage (MB): namely JVM Total memory used . If JVM All available memory is used , This indicator can measure the overall performance of the underlying operating system .
  • Heap memory usage (MB): namely JVM For running Java All memory allocated by the object used by the application . Unused objects are usually removed from the heap by the garbage collector . therefore , If this index increases , Indicates that your application does not remove objects that are not used, or you need to better configure the parameters of the garbage collector .
  • Use of non heap memory (MB): All the memory allocated for the method area and the code cache . Method area is used to store the reference of the loaded class , If these references are not properly cleaned up , The immortal pool will grow every time an application is redeployed , Causes a non heap memory leak . This indicator may also indicate a thread creation leak .
  • Total memory in the pool (MB): namely JVM The memory of all allocated variable memory pools and ( That is, all the memory except the code cache and ). This indicator allows you to identify your application in JVM Total memory available before overload .
  • Threads : That is, the number of all valid threads . for instance , stay Tomcat Each request in the server is handled by an independent thread , So this metric can indicate how many requests there are at present , Does it affect the running of low privilege threads in the background .
  • class : The total number of classes loaded . If your application dynamically creates many classes , This may be one of the reasons for the server memory leak .

One 、 Standard parameters

1.-server  
-client  
Virtual machine server mode / Client mode , Use server Patterns can improve performance , Start up is better than client Slow mode , Long term operation is better than client Fast mode . When this parameter is not specified , The virtual machine starts to detect whether the host is a server , If so, take server mode , Otherwise, we should client mode ,J2SE5.0 The test is based on at least 2 individual CPU And the lowest 2GB Memory   
2.-agentlib:<lib-name>=<options>  
-agentpath:<lib-path>=<options>  
Local class library loading , When some of your classes contain local methods , You need to write your own local code and load the shared package on the operating system (dll) On the way , If you don't like to put the package on an OS aware load , You can load your own local shared package by specifying this parameter (dll). The difference is -agentlib Only the package name is specified in , According to the different operating systems, the virtual machine searches the package on a certain path , For example, for windows Platform virtual machine in PATH Search for the package on the path , and lib-path Is to specify the full path , for example   
-agentlib:hprof stay windows The platform virtual opportunity arrives at PATH Search on the path hprof.dll And load   
The virtual machine has a start operation after loading the agent package ( For details, see JDK Reference resources ),<options> Refers to the startup parameters of the proxy package   
3.-classpath classpath  
-c classpath  
Specify the classpath , System application class loader (ClassLoader) The class will be loaded under this path   
4.-Dproperty=value  
Set system properties , Can pass System.getProperty(property) get   
5.-enableassertions[:<package name>"..." | :<class name> ]  
-ea[:<package name>"..." | :<class name> ]  
-disableassertions[:<package name>"..." | :<class ; ]  
-da[:<package name>"..." | :<class name> ]  
Enable and disable assertions , The default is to disable assertion . Assertion means from JDK1.4 Start with supported keywords assert,assert(booleanvalue), When booleanvalue by false when , Throw out java.lang.AssertionError, It must be noted that , Code compilation must be 1.4 And above obedient , The following parameters are used at compile time   
java -source 1.4  
Generally, assertions are only enabled in the development phase , It's not used in the runtime   
Its use includes the following situations   
java -ea // Start assertion   
java -ea:pkname... // In the bag pkname And its subpackages   
java -ea:pkname.classname // Antitype pkname.classname Enable assertion   
Deactivating assertions is similar to enabling settings   
6.-enablesystemassertions  
-esa  
-disablesystemassertions  
-dsa  
Enable and disable system class assertions   
7.-jar  
Running is contained in a jar The program in the bag , Generally in jar Bag /META-INF/MANIFEST.MF The document specifies Main-Class The value is the main function to run , for example Main-Class:ayufox.ejb3.Test  
8.-javaagent:<classname>[<=options>]  
load java Language agent , The function is JDK5 Newly increased , You can use this setting in JVM Run the main function (main) Do some preprocessing before , among classname Static methods must be included in   
public static void premain(String agentArgs, Instrumentation inst) { ... }  
above options That is, the proxy parameter passed into the function agentArgs, About Instrumentation See package for details java.lang.instrument  
9.-verbose  
-verbose:class  
-verbose:gc  
-verbose:jni  
At run time   
class: Print out the class loading in the console   
gc: Print the garbage collection event information of the virtual machine   
jni: Print local method call information   
-verbose And -verbose:class equally   
10.-version  
-showversion  
Display version information , The difference is that after the first display version, the virtual machine ends and exits   
11.-?  
-help  
Display help message and exit   
12.-X  
Show nonstandard parameters ( See introduction below ) And exit   
Two 、 Nonstandard parameters ( With -X start )  
1.-Xint  
All bytecodes run in parse mode . That's how the first generation of virtual machines ran , Because of the need to Java The parser parses and runs , So the efficiency is relatively low ; The second generation of virtual machine adopts the way of compiling bytecode into local code , The efficiency is greatly improved ; The third generation of virtual machines is also called adaptive (HotSpot) virtual machine , By monitoring the execution of the code, we can detect the frequently executed part of the code , Optimize it to run as local code as possible , And for the ordinary part , Then it runs in analytic mode .  
2.-Xbatch  
Disable background compilation , commonly HotSpot When the virtual machine detects that a piece of code is frequently executed and needs to be compiled into local code , Will start a background thread to complete this work , And at the same time, we continue to run bytecode by parsing . If this parameter is set , Will stop executing bytecode , First compile it into local code , Then continue .  
3.-Xdebug  
-Xnoagent  
-Xrun  
-Xrunjdwp  
Enable debug mode , See above 《 utilize JPDA Build debugging platform 》 This article , I'll describe it in detail in a separate article   
4.-Xbootclasspath:bootclasspath  
-Xbootclasspath/a:path  
-Xbootclasspath/p:path  
Set the boot root Classpath, Even if you start the class loader, where will the object be loaded , About class bootloader , See 《JVM Classloader Architecture 》 explain , The value after the semicolon specifies the path , Separated by semicolons . The difference is ,-Xbootclasspath:bootclasspath Override the default path with the new root load path (\jre\lib \rt.jar),-Xbootclasspath/a:path Combine the new root loading path with the original root loading path ,-Xbootclaspath /p:path Combine the new root loading path with the original root loading path , When loading a class, first search the loading path   
5.-Xcheck:jni  
Call to local (JNI) Adopt more stringent testing methods , It's going on JNI Detect data and incoming parameters before calling , If illegal data is encountered, the virtual machine will be forced to end , Damage to operation performance   
6.-Xfuture  
For class formats (class File format ) Adopt more stringent testing methods , For backward compatibility , It's best to use this parameter at development time   
7.-Xnoclassgc  
Don't use garbage collection   
8.-Xloggc:file  
And -verbose:gc Function as , Difference is that -Xloggc:file Record information into a file , and -verbose:gc Output it to the console  
9.-Xincgc  
-Xmsn  
-Xmxn  
-Xssn  
It's about memory allocation and garbage collection ,-Xincgc Represents progressive garbage collection ,-Xmsn Set the initial memory pool size ,-Xmxn Represents the maximum size allowed for the memory pool ,-Xssn Is the thread stack size ,n Is the value to set , Must be 1024 Multiple , for example   
-Xms6291456 -Xmx83886080  
-Xms6144k -Xmx81920k  
-Xms6m -Xmx80m  
This part is very important to the performance of virtual machine , There will be a separate chapter in the following   
10.-Xprof  
-Xrunhprof[:help][:<suboption>=<value>,...]  
Dissect the runtime , And print the analysis results to the console , The latter can specify a specific profiling object , for example cpu, Pile up (heap) etc. , Can run java -Xrunhprof:help Get objects and values that can be parsed   
11.-Xrs  
Reduce JVM The use of operating system semaphores ,J2SE1.3.1 Start introducing .  
SUN stay J2SE1.3.0 Added in Java Callback hook when the application closes (Hook), For convenience JVM In case of unexpected termination, users can do some resource cleaning work .JVM Monitor console events to achieve JVM Callback on unexpected termination .JVM A console control processor is explicitly registered , When JVM Received CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN When an event is , The processor intervenes to close the return hook (HOOK) To deal with .

If the virtual machine runs as a service ( for example WEB The server ) When it receives CTRL_LOGOFF_EVENT event , Because the system doesn't terminate JVM process , so JVM You can't terminate , However, this conflicts with the above ( Call the close callback hook without ending ), To avoid this problem , from J2SE1.3.1 Use -Xrs In order to make JVM No longer monitor console Events .

One 、         JVM Life cycle of

1.       JVM The instance corresponds to an independent running java Program, it's the process level

a)      start-up . Start a Java The program , One JVM Examples are created , Any one has public static void main(String[] args) Functional class Can be used as JVM Starting point of instance running

b)      function .main() As the starting point of the initial thread of the program , Any other thread is started by that thread .JVM There are two kinds of threads inside : Daemons and non daemons ,main() Belongs to non daemonic thread , The daemons are usually run by JVM Their own use ,java The program can also indicate that the thread created by itself is a guard thread

c)      Extinction . When all non daemons in the program terminate ,JVM Just quit ; If security manager allows , The program can also use Runtime Class or System.exit() To quit

2.       JVM The execution engine instance corresponds to the thread that the user runs the program. It is thread level

Two 、         JVM Architecture of

1.        Class loader (ClassLoader)( For loading .class file )

2.        Execution engine ( Execution bytecode , Or execute local methods )

3.        Run time data area ( Method area 、 Pile up 、java Stack 、PC register 、 Native Method Stack )

3、 ... and 、         JVM Class loader

JVM Steps of the whole class loading process :

1.        load

The loading process is responsible for finding the binary bytecode and loading it into JVM in ,JVM By class name 、 The package name of the class is passed through ClassLoader To complete the loading of the class , Again , The above three elements are also used to identify a loaded class : Class name +

Package name +ClassLoader example ID.

2.        link

The linking process is responsible for verifying the format of binary bytecode 、 Initializes the static variables in the loader class and the interface that is called in the parsing class 、 class .

After verification ,JVM Initializing static variables in a class , And give it the default value .

Finally, for all the properties in the class 、 Method validation , To ensure that it needs to call the properties 、 Methods exist , And have the necessary authority ( for example public、private Domain permissions, etc ), Can cause NoSuchMethodError、NoSuchFieldError Etc .

3.        initialization

The initialization process is to execute the static initialization code in the class 、 Constructor code and initialization of static properties , In four cases, the initialization process is triggered :

Called new;

Reflection calls methods in the class ;

Subclass called initialization ;

JVM The initialization class specified during startup .

JVM Class loading order :

JVM Two types of loaders include : Start class loader and user-defined class loader .

The boot loader is JVM Part of the implementation ;

The user-defined class loader is Java Part of the program , Must be ClassLoader Subclasses of classes .

JVM Loading sequence :

Jvm Startup time , from Bootstrap towards User-Defined Direction loading class ;

The application proceeds ClassLoader when , from User-Defined towards Bootstrap Direction to find and load classes ;

1.       Bootstrap ClassLoader

This is a JVM The root of the ClassLoader, It is to use C++ Realized ,JVM Initialize this ClassLoader, And thus ClassLoader complete $JAVA_HOME in jre/lib/rt.jar(Sun JDK The implementation of the ) All in class Loading of files , This jar It contains java All interfaces and implementations defined by the specification .

2.       Extension ClassLoader

JVM Use this classloader To load some of the extended functions jar package .

3.       System ClassLoader

JVM Use this classloader To load the Classpath Medium jar Packages and directories , stay Sun JDK in ClassLoader The corresponding class name is AppClassLoader.

4.       User-Defined ClassLoader

User-DefinedClassLoader yes Java Developers inherit ClassLoader The abstract class implements itself ClassLoader, Custom based ClassLoader Can be used to load non Classpath Medium jar And directory .

ClassLoader Several key methods of abstract class :

(1)       loadClass

This method is responsible for loading the class with the specified name ,ClassLoader The implementation of is to find... From the loaded class first , If not, continue from parent ClassLoader Search for , If still not found , From System ClassLoader Search for , Last call findClass Ways to find , To change the loading order of classes , You can override this method

(2)       findLoadedClass

This method is responsible for ClassLoader Find the loaded class in the cache of the instance object , Called by native Methods .

(3)       findClass

This method throws ClassNotFoundException, So you need to cover loadClass Or this method to load the corresponding class in a custom way .

(4)       findSystemClass

This method is responsible for System ClassLoader Find classes in , If not found , Then continue from Bootstrap ClassLoader Search for , If you still want to find , Then return to null.

(5)       defineClass

This method is responsible for converting binary bytecode to Class object

(6)       resolveClass

This method is responsible for Class Links to objects , If you have already linked , Will return directly to .

Four 、         JVM Execution engine

When executing a method JVM Four instructions are provided to execute :

(1)invokestatic: The calling class static Method

(2)invokevirtual: Call the method of the object instance

(3)invokeinterface: Define properties as interfaces to make calls

(4)invokespecial:JVM For initialization objects (Java The way to make a constructor is :<init>) And when calling private methods in an object instance .

The main execution technologies are :

explain , Just in time compilation , Adaptive optimization 、 Chip level direct execution

(1) The interpretation belongs to the first generation JVM,

(2) Just in time compilation JIT It belongs to the second generation JVM,

(3) Adaptive optimization ( at present Sun Of HotspotJVM Using this technology ) The first generation JVM And the second generation

JVM Experience , In a way that combines the two

Start to interpret and execute all the code , And monitor code execution , Then start a background thread for those frequently called methods , Compile it into native code , And optimize . If the method is no longer used frequently , Cancel the compiled code , They are still being interpreted and implemented .

5、 ... and 、         JVM Run time data area

First block :PC register

PC Registers are used to store what each thread will do next JVM Instructions , If the method is native Of , be PC No information is stored in the register .

Second pieces :JVM Stack

JVM The stack is thread private , Every thread is created with JVM Stack ,JVM The stack stores the local basic types of variables in the current thread (java The eight basic types defined in :boolean、char、byte、short、int、long、float、double)、 Some of the returned results and Stack Frame, Non basic types of objects are JVM Only one address pointing to the heap is stored on the stack

Third pieces : Pile up (Heap)

It is JVM The area used to store object instances and array values , It can be said that Java All pass new The memory of the created objects is allocated here ,Heap The memory of the object in needs to wait GC To recycle .

(1)        The pile is JVM Shared by all threads in , Therefore, the allocation of object memory on it needs to be locked , It also leads to new The cost of objects is relatively large

(2)       Sun Hotspot JVM In order to improve the efficiency of object memory allocation , A separate space will be allocated for each thread created TLAB(Thread Local Allocation Buffer), Its size is determined by JVM Calculated according to the operation , stay TLAB There is no need to lock when allocating objects on , therefore JVM When allocating memory to a thread's objects, try to TLAB The distribution of , under these circumstances JVM The performance and C It's almost as efficient , But if the object is too large, it still uses heap space allocation directly

(3)       TLAB Acting only on the Cenozoic Eden Space, So I'm writing Java The program , Usually, many small objects are more efficient than large objects .

Fourth pieces : Method area (Method Area)

(1) stay Sun JDK The corresponding area in is PermanetGeneration, Also known as enduring generation .

(2) The method area holds information about the loaded class ( name 、 Embellishments, etc )、 Static variables in class 、 Class is defined as final Constant of type 、 Class Field Information 、 Method information in class , When a developer passes through Class

Object getName、isInterface Wait for the method to get the information , These data are all from the method area , At the same time, the method area is also shared globally , Under certain conditions it will be GC, When the method area needs to use more memory than it allows , Will throw out OutOfMemory Error messages for .

The fifth : Runtime constant pool (Runtime Constant Pool)

It stores fixed constant information in the class 、 Methods and Field Quote information, etc , Its space is allocated from the method area .

The sixth : Local method stack (Native Method Stacks)

JVM Use the local method stack to support native Method execution , This area is used to store each native The state of the method invocation .

6、 ... and 、         JVM Garbage collection

GC The basic principle of : Recycle objects that are no longer in use in memory ,GC The method used for recycling in is called a collector , because GC It takes some resources and time ,Java After analyzing the life cycle characteristics of an object , According to the new generation 、 Old generation way to collect objects , To shorten as much as possible GC Pause for application

(1) The collection of new generation objects is called minor GC;

(2) The collection of old generation objects is called Full GC;

(3) Active call in the program System.gc() Enforced GC by Full GC.

Different object reference types , GC There are different ways to recycle ,JVM There are four types of references to objects :

(1) Strong citation : By default , Objects are all strong references ( The instance of this object has no other object references ,GC It will be recycled )

(2) Soft citation : Soft references are Java This is a more suitable application for caching scenarios ( It's only when there's not enough memory GC)

(3) Weak reference : stay GC You're bound to be GC Recycling

(4) Virtual reference : Because virtual references are only used to know whether an object has been GC

JVM Starting parameters and principle More related articles

  1. NetBeansRCP- add to / modify NetBeans Of JVM Launch parameters

    NetBeans The speed of running is really not flattering . Fortunately, the machine configuration is OK , Modify it JVM Start the parameter command line , In order to run more smoothly . How to modify NetBeans IDE Of JVM What about parameters? ? 1. To NetBeans IDE Safety of ...

  2. JVM Summary of startup parameters

    One :JVM There are three types of startup parameters :         One is the standard parameter (-), be-all JVM The implementation must realize the function of these parameters , And backward compatibility :        The second is non-standard parameters (-X), refer to JVM Some of the underlying configuration parameters , ...

  3. Business system JVM Start parameter recommendation

    Key business systems JVM Start parameter recommendation , Please refer to :http://calvin1978.blogcn.com/articles/jvmoption-2.html

  4. jvm Start parameter settings -Dfile.encoding=UTF-8 solve freemark The statement

    Today one spring boot application windows Run up after the page display garbled , add jvm Start parameters are utf-8 after , Page display normal .

  5. jvm Start parameter settings ( Reprint )

    JVM Launch parameters http://onlyor.iteye.com/blog/1722413 Blog classification : java java java There are three types of startup parameters. One is standard parameters (-), be-all JVM All of these have to be realized ...

  6. Eclipse jvm Where to set the startup parameters

    Learn and reprint from https://jingyan.baidu.com/article/624e7459653ca534e8ba5a26.html Java Is a very popular programming language ,Java Most of our developers make ...

  7. JVM Launch parameters , Will be divided into 3 class

    JVM Launch parameters , Will be divided into 3 class : Category explain Standard parameters (-) be-all JVM The implementation must realize the function of these parameters , And backward compatibility : Nonstandard parameters (-X) These parameters are not specified by the virtual machine specification . therefore , Not all VM The implementation of the ( Such as :H ...

  8. JVM System attribute OS environment variable JVM Launch parameters

    JVM System attribute (System Properties) 1. Viewing and setting system properties through files is not supported 2. Can pass JDK Built-in tools jvisulavm.exe see 3. Can be in Java Used in program API To see the system properties ...

  9. 【java】java obtain JVM Launch parameters System.getProperty

    java obtain JVM Launch parameters System.getProperty take -D After key that will do public class Test { public static void main(String[] arg ...

Random recommendation

  1. Demonstrate how to use db vault Examples of security control

    1. Confirm the database version 2. install db vault Components adopt DBCA To configure db vault: 3. Create test users and tables 4. Create a domain and join users 5. Test Demo

  2. Android New components RecyclerView Introduce , It's more efficient

    Today, let's start with why we want to introduce this new component RecyclerView, Because I released a common interview question a few days ago ListView Reuse and how to optimize the article , Introduce to some developers , But I've seen feedback about it saying : It's not used anymore listv ...

  3. Spring The mechanism of things

    Spring Two kinds of things processing mechanism , One is declarative things , Second, programming things   Declarative things 1)Spring At the bottom, declarative transaction management is based on AOP Based on . Its essence is to intercept before and after the method , Then create or ...

  4. PAT 07-0 Write this number

    Use pinyin to output the sum of each digit of a number , This may be more appropriate than the title above . Here I use it for the first time sprintf()(stdio.h) This function , I was looking for itoa()(stdlib.h) Function , Look up the information , Say this function ...

  5. TComboBox Important properties of components

    TComboBox Important properties of components CharCase-------- This property is used to set the case of the text in the edit box DropDownCount--- This property is used to set the number of items that can be displayed without adding a scroll bar when the user drops down the combo box Dr ...

  6. UIAlertAction Pop-up dialog box 9.0 It's a little bit different after

    ios 9.0 Then use the old one UIAlertAction Not anymore Has been deprecated This way instead UIAlertController *alertController = [UIAlertControlle ...

  7. MHA The steps and principles of online switching

    In daily work , You will encounter the following scenes , Such as mysql Database upgrade , Main server hardware upgrade, etc , At this time, you need to switch the write operation to another server , So how to switch online ? meanwhile , The switching process is required to be short , The impact on the business is relatively small . MHA Just mention ...

  8. The first 58 section :Java Graphical interface programming in -GUI

    Welcome to my short book to see my anthology Preface : GUI It's a graphical user interface , stay Java in , Graphical user interface we use GUI Express , and GUI The complete English is : Graphical User Interface( Graphical user interface ), The so-called graph ...

  9. Sublime Text3 The latest version V3.1.1 build3117 Registration code , It's a perfect way to activate ~

    Sublime Text 3 The latest registration code The latest version downloaded from the official website V3.1.1 build3117, Pro test the following registration code can be activated normally ----- BEGIN LICENSE ----- sgbteam Singl ...

  10. div+css A complete collection of names

    head :header   Content :content/container   tail :footer   Navigation :nav   Sidebar :sidebar  The column :column The page periphery controls the overall layout width :wrapper   Right and left :lef ...