Java The access operations defined in the virtual machine memory model are basically consistent with those processed by the physical computer ！
Java The multithreading mechanism enables multiple tasks to execute processing at the same time , All threads share JVM Memory area main memory, Each thread has its own working memory , When a thread interacts with a memory area , Copy data from main memory to working memory , Then let the thread handle （ opcode + Operands ）. We'll see more information later 《 thorough JVM—JVM Class execution mechanism 》.
Before , We have also mentioned ,JVM The logical memory model is as follows ：
Now let's take a look at what each does one by one ！
Program counter （Program Counter Register） It's a small amount of memory , It can be thought of as a line number indicator of the bytecode being executed by the current thread . In the conceptual model of virtual machines （ Conceptual model only , Various virtual machines may be implemented in more efficient ways ）, The bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to execute , Branch 、 loop 、 Jump 、 exception handling 、 Basic functions such as thread recovery rely on this counter .
because Java Multithreading of virtual machine is realized by the way that threads switch in turn and allocate processor execution time , At any given moment , A processor （ It is a kernel for a multicore processor ） Only one instruction in a thread is executed . therefore , In order to recover to the correct execution position after thread switching , Each thread needs to have a separate program counter , The counters between threads do not affect each other , Independent storage , We call this kind of memory area “ Thread private ” Of memory .
If the thread is executing a Java Method , This counter records the address of the virtual machine bytecode instruction being executed ; If what is being executed is Natvie Method , The counter value is null （Undefined）. This memory area is the only one in Java Nothing is specified in the virtual machine specification OutOfMemoryError Area of situation .
Same as the program counter ,Java Virtual machine stack （Java Virtual Machine Stacks） It's also thread private , It has the same life cycle as a thread . The virtual stack describes Java Memory model for method execution ： Each method is executed with a stack frame created at the same time （Stack Frame ①） Used to store local variables 、 Stack operation 、 Dynamic links 、 Method exit information . Each method is called until the procedure completes , This corresponds to the process of a stack frame in the virtual machine stack from push to push .
People often put Java Memory is divided into heap memory （Heap） And stack memory （Stack）, This method is rough ,Java The partition of memory area is actually much more complicated than that . The popularity of this division only shows that most programmers are most concerned about it 、 The two most closely related memory areas to object memory allocation are . Which refers to “ Pile up ” I'll talk about it later , And the “ Stack ” This is the virtual machine stack , Or the local variable table in the virtual machine stack .
The local variometer holds various basic data types known at compile time （boolean、byte、char、short、int、float、long、double）、 Object reference （reference type , It's not the same as the object itself , According to different virtual machine implementation , It might be a reference pointer to the starting address of the object , It may also point to a handle representing an object or other location related to the object ） and returnAddress type （ Points to the address of a bytecode instruction ）.
among 64 A length of long and double Type of data is occupied 2 The local variable space （Slot）, The rest of the data types are occupied only 1 individual . The memory space required for local variables is allocated during compilation , When entering a method , The amount of local variable space that this method needs to allocate in the frame is completely determined , The local variometer size does not change during method run .
stay Java In the virtual machine specification , Two kinds of anomalies are specified for this region ： If the stack depth of the thread request is greater than the depth allowed by the virtual machine , Will throw out StackOverflowError abnormal ; If the virtual machine stack can be expanded dynamically （ Most of the current Java Virtual machines can be dynamically expanded , It's just Java Fixed length virtual machine stack is also allowed in the virtual machine specification ）, Thrown when the extension cannot request enough memory OutOfMemoryError abnormal .
Native Method Stack （Native Method Stacks） It's very similar to what the virtual machine stack does , The difference is that the virtual machine stack executes for the virtual machine Java Method （ That's bytecode ） service , The local method stack is used by the virtual machine Native Method service . The language used in the VM specification for methods in the native method stack 、 Usage and data structure are not mandatory , So the virtual machine can realize it freely . Even some virtual machines （ for example Sun HotSpot virtual machine ） Directly combine the local method stack and virtual machine stack into one .
Same as the virtual machine stack , The local method stack area is also thrown StackOverflowError and OutOfMemoryError abnormal .
For most applications ,Java Pile up （Java Heap） yes Java The largest chunk of memory managed by a virtual machine .Java The heap is an area of memory Shared by all threads , Created when the virtual machine starts . The sole purpose of this memory area is to hold object instances , Almost all object instances allocate memory here . This is in Java The description in the virtual machine specification is ： All object instances and arrays are allocated on the heap ①, But as the JIT The development of compiler and the maturity of escape analysis technology , On the stack 、 Scalar substitution ② Optimization techniques will lead to subtle changes , All the objects are distributed on the heap, and it's becoming less and less “ absolute ” 了 .
Java The heap is the main area managed by the garbage collector , So it's also called “GC Pile up ”（GarbageCollected Heap, Fortunately, there is no translation in China “ rubbish dump ”）. From the perspective of memory recycling , Because now the collector is basically a generational collection algorithm , therefore Java The heap can also be subdivided into ： The new and the old ; More detailed Eden Space 、From Survivor Space 、To Survivor Space etc. . From the perspective of memory allocation , Thread shared Java Multiple thread private allocation buffers may be partitioned in the heap （Thread LocalAllocation Buffer,TLAB）. however , No matter what , It has nothing to do with the storage , No matter which area , Objects are still stored , The purpose of further partitioning is to better reclaim memory , Or allocate memory faster . In this chapter , We only discuss the function of memory area ,Java The details of the allocation and recycling of the above areas in the heap will be the subject of the next chapter .
according to Java The specification of the virtual machine specification ,Java The heap can be in a physically discontinuous memory space , As long as it's logically continuous , It's like our disk space . At the time of implementation , It can be realized as a fixed size , It can also be extensible , However, the current mainstream virtual machines are implemented according to scalability （ adopt -Xmx and -Xms control ）. If there is no memory in the heap to complete the instance allocation , And the heap cannot be extended , It will be thrown out. OutOfMemoryError abnormal .
Method area （Method Area） And Java Pile up , Is an area of memory Shared by each thread , It is used to store class information that has been loaded by the virtual machine 、 Constant 、 Static variables 、 Real time compiler compiled code and other data . although Java The virtual machine specification describes the method area as a logical part of the heap , But it has an alias called Non-Heap（ Non heap ）, The purpose should be with Java Heap differentiation .
For habits in HotSpot For developers who develop and deploy programs on virtual machines , Many people like to call the method area “ Forever ”（Permanent Generation）, They're not essentially equivalent , Just because HotSpot Virtual machine design team chooses GC Generational collection extends to the method area , Or use permanent generation to implement method areas . For other virtual machines （ Such as BEA JRockit、IBM J9 etc. ） There is no concept of permanent generation . Even if it's HotSpot Virtual machine itself , According to the official road map , Now, there are also those who give up and live forever “ house-moving ” to Native Memory To realize the planning of the method area .
Java This is a very loose area for virtual machines , Except for and Java The heap does not need continuous memory and can be fixed size or expandable , You can also choose not to implement garbage collection . Relatively speaking , Garbage collection is relatively rare in this area , But it's not the data that goes into the method area like the name of the permanent generation “ permanent ” There is . The target of this area is to recycle the constant pool and unload the type , In general this area of recycling “ achievement ” More unsatisfactory , In particular, type uninstall , The conditions are pretty tough , But the recycling of this part of the area is really necessary . stay Sun The company's BUG In the list , There have been several serious ones BUG Because of the lower version HotSpot The virtual machine has not fully reclaimed this area, resulting in a memory leak .
according to Java The specification of the virtual machine specification , When the method area cannot meet the memory allocation requirements , Will throw out OutOfMemoryError abnormal .
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 PoolTable）, 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 . But for runtime constant pools ,Java The virtual machine specification does not require any details , Virtual machines implemented by different providers can implement this memory area according to their own needs . however , Generally speaking , In addition to save Class Outside of the symbol reference described in the file , The translated direct references are also stored in the runtime constant pool ①.
Runtime constant pool relative to Class Another important feature of file constant pool is its dynamic nature ,Java The language does not require constants to be generated only at compile time , It's not preset Class The contents of the constant pool in the file can enter the method area runtime constant pool , It is also possible to pool new constants during runtime , This feature is used more by developers String Class intern() Method .
Since the runtime constant pool is part of the method area , The method area memory is naturally limited , When the constant pool can no longer request memory, it will throw OutOfMemoryError abnormal
Direct memory （Direct Memory） It's not part of the virtual machine runtime datazone , Neither Java Memory area defined in virtual machine specification , But this part of memory is also frequently used , And it can also lead to OutOfMemoryError Abnormal appearance , So we're going to talk about it here .
stay JDK 1.4 Newly added NIO（New Input/Output） class , A channel based approach is introduced （Channel） With the buffer （Buffer） Of I/O The way , It can be used Native Function library directly allocates out of heap memory , And then through a Java In the pile DirectByteBuffer Object operates as a reference to this memory . This can significantly improve performance in some scenarios , Because it avoids Java Heaps and Native Copy data back and forth in the heap .
obviously , The allocation of local direct memory will not be affected Java Heap size limits , however , Since it's memory , Then the total memory of the machine will be received （ Include RAM And SWAP Area or paging file ） The size of the processor and the limit of addressing space . When the server administrator configures the virtual machine parameters , Generally, it will be set according to the actual memory -Xmx Isoparametric information , But direct memory is often ignored , Make the sum of each memory area greater than the physical memory limit （ Including physical and operating system level limitations ）, This leads to the emergence of dynamic expansion OutOfMemoryError abnormal
The logical memory model we've seen , How do we access an object when we create it ？ stay Java In language , How object access works ？ Object access in Java Language is everywhere , It's the most common procedural behavior , But even the simplest access , It will also involve Java Stack 、Java Pile up 、 Method area the relationship between the three most important memory areas , As the code below ：
Object obj = new Object();
Suppose the code appears in the method body , that “Object obj” The semantics of this part will reflect Java In the local variables table of the stack , As a reference Type data appears . and “new Object()” The semantics of this part will reflect Java In the pile , Form a piece of storage Object Type all instance data values （Instance Data, Data of each instance field in the object ） Of structured memory , According to the specific type and the object memory layout of the virtual machine （Object Memory Layout） Different , The length of this memory is not fixed . in addition , stay Java The heap must also contain data that can be found to this object type （ Such as object type 、 Parent class 、 Implemented interface 、 Such method ） Address information for , These types of data are stored in the method area .
because reference Type in the Java The virtual machine specification only specifies a reference to an object , There is no definition of how this reference should be located , And visit Java The specific location of the objects in the heap , So different virtual machines implement different object access methods , There are two main ways of visiting ： Use handles and direct pointers .
If you use handle access ,Java A block of memory will be divided in the heap as a pool of handles ,reference Is the handle address of the object , The handle contains the specific address information of the object instance data and type data , As shown in the figure below .
If you use direct pointer access ,Java The layout of heap objects must consider how to place information about access type data ,reference The object address is directly stored in the , As shown in the figure below
These two ways of accessing objects have their own advantages , The biggest benefit of using handle access is reference A stable handle address is stored in , When the object is moved （ Moving objects during garbage collection is a very common behavior ） Will only change the instance data pointer in the handle , and reference It doesn't need to be modified .
The biggest benefit of using direct pointer access is that it's faster , It saves the time cost of a pointer location , Because the access of the object Java Very often , Therefore, this kind of overhead is also a very considerable execution cost . Main virtual machines discussed in this book Sun HotSpot for , It uses the second way to access objects , But from the perspective of the whole scope of software development , It is also common for languages and frameworks to use handles for access .
In the following procedure, we limit Java The heap size is 20MB, Non scalable （ The minimum value of the heap -Xms Parameters and maximum -Xmx Set the parameter to the same to avoid automatic heap expansion ）, Through parameters -XX:+HeapDumpOnOutOfMemoryError Can let virtual machine in the event of memory overflow exception Dump Take a snapshot of the current memory heap dump for later analysis .
The parameters are set as follows
Before the interview, you must brush the questions , In order to facilitate everybody to review , I'd like to share a collection of personal interviews
- Java Organize the core knowledge
Java Core knowledge
- Spring Family bucket （ Practical series ）
- Other ebook materials
Step3： Brush problem
Since it's an interview , Then it's necessary to brush the questions , In fact, after the Spring Festival home , I can't go anywhere , I did a lot of interview questions myself , So in the interview process to be able to know , Basically, it will be clear what knowledge points will be asked during the interview , What are the high frequency questions , So brushing questions is a very important point in the pre interview preparation process .
The following is my private interview question bank ：