Today’s sharing started, please give us more advice ~
Approaching autumn recruitment, preparing for summer internship, I wish you every day progress hundred million little! This article summarizes interview questions related to the JVM.
1. Briefly describe the Java memory structure (runtime data area)
① Program counter
Program counter: Thread private. A small memory space where the program counter holds the address of the next bytecode instruction to be executed in the JVM! If the Native method is being executed, this counter value is null. Program counters are implemented at the hardware level through registers!
Java instruction execution process:
- The.java code source files are compiled into.class binary bytecode files.
- Each binary bytecode instruction (JVM instruction) in the.class file is converted into machine code by the interpreter, which can then be executed by the CPU!
- When the interpreter converts a JVM instruction into machine code, it also delivers the address of the execution of the next JVM instruction to the program counter!
As shown in the figure:
② Virtual machine stack
Virtual stack: The thread is private and has the same lifetime as the thread. The virtual machine stack is an in-memory model for Java method execution. Each method execution creates a stack frame to store information about local variables, operand stacks, dynamic links, method exits, and so on. The process of each method from being called to completion corresponds to the process of a stack frame being pushed into and out of the virtual machine stack.
- Each stack consists of multiple stack frames, corresponding to the memory occupied by each method at runtime.
- Each thread can have only one active stack frame, corresponding to the currently executing method, which is pushed when the method is executing and ejected when the method is finished.
- Reference variables and variables of primitive types in the method body are on the stack, and everything else is on the heap.
Example code:
Process analysis:
Let’s interrupt to Debug to see how the method executes:
Then proceed down to complete method B:
Then, after the execution of method A, its corresponding stack frame is out of the stack, and the corresponding stack frame of main method is active stack frame; Finally, the main execution finished, stack frame out of the stack, virtual machine stack is empty, the end of the code run!
③ Local method stack
Local method stack: Thread private. The role of the Native method stack is very similar to that of the virtual machine stack, except that the virtual machine stack performs Java method (that is, bytecode) services for the virtual machine, while the Native method stack serves the Native methods used by the virtual machine.
Some methods with native keyword modifications require JAVA to call native C or C++ methods, because JAVA sometimes can’t directly interact with the underlying operating system, so you need to use native methods!
(4) the heap
Heap: Thread sharing. The Java heap is the largest chunk of memory managed by the Java Virtual machine. It is an area of memory shared by all threads and created when the virtual machine is started. The sole purpose of the Java heap is to hold object instances, and almost all object instances are allocated here.
- Objects created with the new keyword are placed in the heap memory.
- Reference variables and variables of primitive types in the method body are on the stack, and everything else is on the heap.
- The Java heap is the primary area managed by the Garbage collector, and is often referred to as the “GC heap.”
- -xmx-xms: The initial heap allocated by the JVM is specified by -xms, which defaults to 1/64 of the physical memory.
(5) method area
Method area: thread sharing. The method area is used to store * class information (constructors, interface definitions), constants, static variables, code compiled by the just-in-time compiler (bytecode) * that has been loaded by the virtual machine.
- The method area is created at JVM startup, and its actual physical memory space can be as discontinuous as the Java heap. Shutting down the JVM frees up memory in this area.
- The size of the method area determines how many classes the system can hold. If the system defines too many classes and causes the method area to overflow, the VIRTUAL machine will also throw an overflow error: (Java. Lang. OutOfMemoryError: PermGen space, Java, lang, OutOfMemoryError: Metaspace).
Note: The method area is a specification, and the permanent generation and meta-space are two implementations of it.
Method area evolution:
Version 1.6 method areas are implemented by persistent generations (using a portion of heap memory as method areas) and managed by the JVM. Consists of Class, ClassLoader, and constant pool (including StringTable).
Version 1.7 of the Jdk still has persistent generations, but has progressively “de-perpetuated” stringtables, static variables removed from the permanent generation and stored in the heap.
After version 1.8, the method area was handed over to local memory management, not the JVM, and implemented in a meta-space (which no longer uses heap memory, but local memory, i.e. operating system memory), consisting of classes, classLoaders, and constant pools (stringtables were moved to the heap for management).
⑥ Runtime constant pool
Constant pool: Can be thought of as a table from which virtual machine instructions find the class names, method names, parameter types, literals, and so on to execute.
- The constant pool is in a *.class file. When the class is loaded, its constant pool information is put into the runtime constant pool and the symbolic addresses in it are converted into real memory addresses.
Runtime constant pool: is part of the method area.
String str = new String(“hello”);
In the above statement, the variable STR is placed on the stack, the string object created with new is placed on the heap, and the hello literal is placed on the heap.
Does JVM garbage collection involve stack memory?
Don’t need. Because the virtual machine stack is composed of stack frames, the corresponding stack frame will be removed from the stack after the method is executed. There is no need to recycle memory through garbage collection.
3. Is the larger allocation of vm stack memory the better?
It isn’t. Because physical memory is fixed, the larger the stack memory, the more recursive calls it can support, but the fewer threads it can execute.
Let’s look at a picture:
For example, if the physical memory is 500 MB (let’s say), and if the stack memory allocated by one thread is 2 MB, then there could be 250 threads. If one thread allocates 5M of stack memory, then at most 100 threads can execute simultaneously!
Are local variables in methods thread-safe from the PERSPECTIVE of the JVM?
Let’s analyze it through two graphs:
Case 1:
Situation 2:
It follows from the diagram that local variables that are static and can be shared by multiple threads are thread-safe. If it is non-static and only exists in the scope of a method and is private to the thread, then it is thread-safe!
Here’s another example:
So, the answer to the interview question is:
Local variables within a method are thread-safe if they do not escape the scope of the method.
If a local variable references an object and escapes the scope of a method, thread-safety concerns need to be considered.
5. What are the cases of vm stack memory overflow?
- It is not uncommon for virtual machine stacks to run out of stack memory due to excessive stack frames (methods are infinitely recursive)!
- It is rare that each stack frame occupies too much memory (one or more stack frames directly exceed the maximum memory of the virtual machine stack)!
As shown in the figure, there are too many stack frames in the stack:
6. Describe the evolution of the JVM runtime data area method area.
Version 1.6 method areas are implemented by persistent generations (using a portion of heap memory as method areas) and managed by the JVM. Consists of Class, ClassLoader, and constant pool (including StringTable).
- Static variables are stored on the permanent generation (method area).
Version 1.7 of the Jdk still has persistent generations, but has progressively “de-perpetuated” stringtables, static variables removed from the permanent generation and stored in the heap.
After version 1.8, the method area was handed over to local memory management, not the JVM, and implemented in a meta-space (which no longer uses heap memory, but local memory, i.e. operating system memory), consisting of classes, classLoaders, and constant pools (stringtables were moved to the heap for management).
- Static variables, stringTables in the heap!
Why do we replace permanent generations with meta-spaces?
Because the permanent generation has the following disadvantages:
The string constant pool exists in the permanent generation. If a large number of strings are used, OOM exceptions are likely to occur.
② It is difficult to determine the total number of classes loaded by the JVM, the size of methods, etc., so it is difficult to specify the permanent generation size. If the permanent generation is too small, the memory of the permanent generation will overflow. If the permanent generation is too large, the MEMORY of the VM will be strained and space will be wasted.
(3) It is difficult to tune the permanent generation: the garbage collection of the method area mainly recycles two parts: discarded constants and classes that are no longer used in the constant pool. Classes that are no longer used or whose loaders are collected are more complex and FULL GC takes longer.
What class loaders are available in the Java virtual machine?
Take JDK 8 as an example:
The priority of class loaders (in descending order) is: start class loaders -> Extension class loaders -> application class loaders -> Custom class loaders.
-
** Bootstrap ClassLoader: ** This class loader is responsible for storing it in the JAVA_HOME/jre/lib directory, or in the path specified by the -xbootclasspath parameter, and is recognized by the virtual machine (only by the file name, such as rt.jar, Libraries with incorrect names will not be loaded even if placed in the lib directory.) Libraries are loaded into the virtual machine memory.
-
** Extension ClassLoader: ** This loader is implemented by sun.misc.Launcher$ExtClassLoader, which is responsible for loading all class libraries in the JAVA_HOME/jre/lib/ext directory, or in the path specified by the java.ext.dirs system variable. Developers can use the extended class loader directly.
-
Application ClassLoader: This ClassLoader is implemented by sun.misc.Launcher$AppClassLoader. Since this ClassLoader is the return value of the getSystemClassLoader() method in ClassLoader, it is also commonly referred to as the system ClassLoader. It is responsible for loading the libraries specified on the user’s ClassPath. Developers can use this class loader directly, and this is generally the default class loader if the application does not have its own custom class loader.
-
** Custom class loaders: ** User-defined class loaders.
8. Could you describe the loading process of a class?
The process of class loading includes: loading, validating, preparing, parsing, and initializing. Validation, preparation, and parsing are collectively referred to as connections.
-
Load: Generates a java.lang.Class object in memory that represents a Class by obtaining the binary byte stream that defines that Class by its fully qualified name.
-
Verification: Ensures that the byte stream in the Class file meets the requirements of the current VM and does not compromise vm security.
-
Preparation: Allocates memory for static variables and sets initial values for static variables, which are “normally” zero values for the data type.
-
Parse: Replace symbolic references in the constant pool with direct references.
-
Initialization: During the initialization phase, you actually start executing the Java initializer code defined in the class. Mainly static variable assignment actions and statements in the static statement block (static{}).
9. What is the parental delegation model?
As shown in the figure:
What is the parental delegation model?
If a classloader receives a classload request, it does not try to load the class itself at first. Instead, it delegates the request to the parent classloader. This is true at every level of classloaders, so all load requests should eventually be passed to the top level of the starting classloader. Only when the parent loader reports that it cannot complete the load request (it did not find the desired class in its search scope) will the child loader attempt to load it itself.
Why use the parent delegate model? (good)
Avoid reloading + Avoid core class tampering
-
The advantage of the parent delegate pattern is that Java classes have a hierarchy of priorities with their classloaders. This hierarchy avoids reloading classes, and there is no need for child loaders to reload classes when the parent has already loaded the class.
-
Second, for security reasons, defined types in the Java core API will not be arbitrarily replaced. Suppose that a class named java.lang.Integer is passed over the network through the parent delegate mode to the launcher class loader, and the launcher class loader finds this name in the core Java API. If the class is loaded, instead of reloading the java.lang.Integer passed by the network, integer.class is returned, which prevents the core API library from being tampered with.
What is the difference between a virtual stack and a heap?
① Differences in physical address:
-
The heap’s physical address assignment is discontinuous to objects. So the performance is slower.
-
Virtual machine stack uses the stack of data structure, the principle of first in last out, physical address allocation is continuous. So the performance is fast.
② Differences in memory allocation:
-
Heap: Because it is discontinuous, the allocated memory is acknowledged at run time and therefore the size is not fixed. The average heap size is much larger than the virtual machine stack.
-
The virtual stack is contiguous, so the allocated memory size is determined at compile time and is fixed.
③ The difference in the content of storage:
-
Heap: Holds instances and arrays of objects. Therefore, the area is more concerned with data storage.
-
The virtual machine stack holds local variables, operand stacks, and returns results. The district is more concerned with the implementation of procedural methods.
Note: Static variables are placed in the method area, while static objects are placed in the heap.
④ Differences in thread sharing:
-
Heap: Is shared and visible to the entire application.
-
Virtual stack: only visible to threads. So it’s also thread private. Its life cycle is the same as that of a thread.
Today’s share has ended, please forgive and give advice!