Complete JVM learning notes please click here

Memory and Threads

01 memory

Memory is a very important system resource. It is the intermediate warehouse and bridge between hard disk and CPU, carrying the operating system and application program running in real time. The JVM memory layout defines the JAVA memory allocation, allocation, and management strategies during the running process, ensuring efficient and stable running of the JVM. There are some differences in the way memory is divided and managed by different JVMS (in the case of Hotspot, the method area)

02 Zone Introduction

The Java virtual machine defines several run-time data areas that are used by programs during their execution, some of which are created when the virtual machine is started and destroyed when the virtual machine exits. Others correspond to counties one by one, and these threads correspond to data areas that are created and destroyed as threads start and end. As shown in the figure, the gray area is private to a single thread, while the red area is shared by multiple threads, i.e

  • Each thread: independently includes program counter, stack, local stack
  • Interthread sharing: heap, off-heap memory (method area, permanent generation or meta-space, code cache)

In general, 95% of JVM optimizations are for heap areas and 5% for method areas

03 thread

  • Threads are the unit of execution within a program, and the JVM allows multiple threads to execute a program in parallel.
  • In HotSpot JVM, each thread maps directly to the operating system’s native thread.
    • When a Java thread is ready to execute, an operating system native thread is created at the same time. Java thread execution terminates. Local threads are also recycled.
  • The operating system is responsible for scheduling all threads to any available CPU. Once the local thread initializes successfully, it calls the run () method in the Java thread.

2.1 JVM System Threads

  • If you use JConsole or any debugging tool, you can see that there are many threads running in the background. These background threads do not include the main thread that calls the main method and all threads created by the main thread itself;
  • The main backend threads in the HotSpot JVM are:
    • Virtual machine thread L is a thread whose operation does not occur until the JVM reaches a safe point. The reason these operations must occur in different threads is that they all need the JVM to reach a safe point so that the heap does not change. This thread execution includes “stop-the-world” garbage collection, thread stack collection, thread suspension, and partial lock cancellation
    • Periodic task threads: These threads are withdrawals of periodic events (such as interrupts) and are typically used for scheduled execution of periodic operations.
    • GC thread: This thread provides support for different kinds of garbage collection behavior in the JVM
    • Compilation thread: This thread reduces bytecode compilation costs at run time
    • Signal scheduling thread: This thread receives signals and sends them to the JVM for processing within it by calling the appropriate methods.

1. Program counter (PC register)

The Program Counter Register in the JVM is named after the CPU Register, which stores instruction related field information. The CPU can only run if it loads data into a register. The PC register in the JVM is an abstract simulation of the PC register in the house

1.1 role

The PC register is used to store the address pointing to the next instruction and the instruction code to be executed. The execution engine reads the next instruction.

  • It’s a small, almost negligible amount of memory. It is also the fastest storage area
  • In the JVM specification, each thread has its own program counter, which is thread-private and whose lifetime is consistent with that of the thread
  • There is only one method executing per thread at any one time, which is called the current method. The program counter stores the JVM instruction address of the Java method being executed by the current thread; Or, if the native method is executed, undefined.
  • It is an indicator of program control flow, and basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on rely on this counter
  • The bytecode interpreter works by changing the value of this counter to select bytecode instructions that need to be executed by surprise
  • It is the only area where the Java Virtual Machine specification does not specify any OOM condition

1.2 Code Examples

Decompile bytecode files using Javap -v xxx.class to view instructions and other information

1.3 Common Interview questions

1. What is the use of using PC registers to store byte code instruction addresses? / Why use the PC register to record the execution address of the current thread? Because the CPU is constantly switching threads, when it comes back, Have to know where to begin then continues executing JVM bytecode interpreter is by changing the PC register values are needed to clear a what kind of bytecode instruction should be executed under 2. Why is set to PC register thread private we all know that the so-called multithreaded refers back to the execution within a specific time period in which a thread, CPU will constantly do task switching, which will inevitably lead to frequent interruption or recovery, how to ensure that the score is not bad? In order to accurately record the address of the current bytecode instructions being executed by each thread, it is naturally best to assign each thread a PC register so that each thread can compute independently without interfering with each other. Due to the CPU time wheel limit, a single processor or core of a multi-core processor will execute only one instruction in a particular thread at any given time during the concurrent execution of multiple threads. This will inevitably lead to frequent interruptions or recovery, how to ensure that there is no difference? After each thread is created, it will generate its own program counter and stack frame. Program counter does not affect each thread.

CPU time slice

The CPU time slice is the time that the CPU allocates to each program. Each thread is allocated a time slice. It’s called its time slice. On a macro level: we can have multiple applications open at the same time, each running in parallel. But on a micro level: since there is only one CPU and only a portion of the program’s requirements can be processed at a time, one way to deal with fairness is to introduce time slices that each program executes in turn. Parallel and concurrent parallelism: multiple threads are executing simultaneously; Concurrency: A core quickly switches multiple threads so that they execute in sequence, which looks like parallelism but is actually concurrency


* 2. Vm stack

2.1 an overview of the

2.1.1 background

Due to its cross-platform design, Java’s instructions are designed on a stack basis. Different platforms have different CPU architectures, so they cannot be register-based. Advantages are cross-platform, small instruction set, compiler easy to implement, disadvantages are performance degradation, to achieve the same function requires more instructions.

2.1.2 Heap and stack in memory

  • The stack is the unit of runtime, and the heap is the unit of storage: the stack solves the problem of how programs run, how programs execute, or how they process data. The heap solves the problem of data storage, how and where data is stored.
  • In general, objects are mostly in heap space, a large part of the run-time data area
  • Stack space holds local variables of the base data type and references to objects that reference the data type

2.1.3 What is a VM Stack

  • Java Virtual Machine Stack (Java Virtual Machine Stack), also known as the Java Stack. Each thread creates a virtual machine Stack, which holds Stack frames for each Java method call. It is thread private
  • The lifecycle is consistent with threads
  • Function: Manages the execution of Java programs. It holds local variables of methods (8 basic data types, reference addresses of objects), partial results, and participates in method calls and returns.
    • Local variable: relative to a member variable (or attribute)
    • Basic data variables: as opposed to reference type variables (classes, arrays, interfaces)

2.1.4 Characteristics of the stack

  • Stack is a fast and efficient way to allocate storage, second only to PC registers (program counters) in access speed
  • The JVM has only two direct operations on the Java stack
    • Each method executes with a push (push, push)
    • Exit the stack after execution
  • There is no garbage collection problem for the stack

2.1.5 Possible Exceptions in the stack

The Java Virtual Machine specification allows the size of the Java stack to be dynamic or fixed

  • With a fixed size Java virtual machine stack, the size of the Java virtual machine stack for each thread can be selected independently at thread creation time. The Java virtual machine will throw a StackOverFlowError if the thread request allocates more stack capacity than the maximum allowed by the Java virtual machine stack
Public class StackErrorTest {public static void main(String[] args) {main(args); }}Copy the code
  • The Java virtual machine will throw an OutOfMemoryError if the Java virtual machine stack can expand dynamically and cannot claim enough memory when attempting to expand, or if there is not enough memory to create the corresponding virtual machine stack when creating a new thread

2.1.6 Setting the stack memory Size

We can use the -xSS option to set the maximum stack space for a thread. The stack size directly determines the maximum reachable depth of a function call. (IDEA setting method: run-Editconfigurations -VM options Specifies the stack size -xss256K)

/** * display stack exception ** Default: count 10818 * set stack size:  -Xss256k count 1872 */ public class StackErrorTest { private static int count = 1; public static void main(String[] args) { System.out.println(count); count++; main(args); }}Copy the code

2.2 Storage structure and operating principle of stack

2.2.1

  • Each thread has its own Stack, and the data in the Stack is stored in the format of Stack frames
  • Each method being executed on this thread corresponds to its own stack frame
  • A stack frame is a block of memory, a data set that holds various data information during the execution of a method
  • The JVM operates directly on the Java stack only two times, namely, on and off the stack frame, following the principle of fifo/LIFO and fifO.
  • In an active thread, there is only one active stack frame at a time. That is, only the stack Frame (top stack Frame) of the currently executing method is valid. This stack Frame is called the Current Frame, and the corresponding method is the Current Frame.
  • All bytecode instructions run by the execution engine operate only on the current stack frame
  • If another method is called in this method, a new stack frame is created and placed at the top of the stack as the new current stack frame.
  • The stack frames contained in different threads are not allowed to reference each other, that is, it is impossible to reference another thread’s stack frame in another stack frame
  • If the current method calls another method, when the method returns, the current stack frame will return the execution result of this method to the previous stack frame, and then the virtual machine will discard the current stack frame, making the previous stack frame become the current stack frame again
  • Java methods have two ways of returning functions. One is to return a normal function using a return directive. The other is to throw an exception. Either way, the stack frame will be ejected.

Public StackFrameTest {public static void main(String[] args) {public static void main(String[] args) {StackFrameTesttest= new StackFrameTest(); test.method1(); Output method1() and method2 () both appear twice as current stack frames, and method3 () once // method1() starts executing... // method2() starts executing... // method3() // method3() // method2() End... // method1() End... } public voidmethod1(){
        System.out.println("Method1 () starts executing...");
        method2();
        System.out.println("Method1 () completes execution...");
    }

    public int method2(){
        System.out.println("Method2 () starts executing...");
        int i = 10;
        int m = (int) method3();
        System.out.println("Method2 () completes execution...");
        return i+m;
    }

    public double method3(){
        System.out.println("Method3 () starts executing...");
        double j = 20.0;
        System.out.println("Method3 () Completes execution...");
        returnj; }}Copy the code

2.2.2 Internal structure of stack frames

Each stack frame stores:

  • Local Variables
  • Operand Stack (or expression Stack)
  • Dynamic Linking (or method reference that performs runtime constant pooling)
  • Method Return address (or definition of method normal or abnormal exit)
  • Some additional information

2.3 Local Variables

2.3.1 overview

  • A local variable list is also called a local variable array or a local variable list
  • An array of numbers used to store method parameters and local variables defined in the method body. These data types include various basic data types, object references, and returnAddressleixing
  • Since the local variable table is built on the thread stack and is thread private data, there is no data security problem
  • The size required by the local variables table is determined at compile time and stored in the Maximum Local Variables data item in the Code attribute of the method. The size of the local variable scale does not change during method execution
  • The number of nested calls to a method is determined by the stack size. In general, the larger the stack, the more nested method calls. For a function, the more arguments and local variables it has, the larger the stack frame will be to meet the need for more information to be passed through method calls. In turn, function calls take up more stack space, resulting in fewer nested calls.
  • Variables in the local variable table are only valid in the current method call. During method execution, the virtual machine passes the parameter values to the parameter variable list using the local variable table. When the method call ends, the local variable table is destroyed along with the method stack frame.

Use javap command to parse the bytecode file and view the local variation table, as shown in the figure:

2.3.2 Understanding and demonstrating variable Slot

  • Parameter values are always stored at index0 of the local variable array and end at the index of the array length -1
  • Local variable scale. The most basic storage unit is Slot.
  • Local variable table stores various basic data types (8 kinds), reference types and variables of returnAddress type known at compilation time.
  • In the list of local variables,Types up to 32 bits occupy only one slot (including the returnAddress type), while 64-bit types (long and double) occupy two slots.
    • Byte, short, char, and float are converted to int before storage. Boolean is also converted to int, with 0 indicating false and non-0 indicating true.
    • Long and double occupy both slots.
  • The JVM assigns an access index to each slot in the local variable table, which successfully accesses the value of the local variable specified in the local variable table
  • When an instance method is called, its method parameters and local variables defined inside the method body are copied to each slot in the local variable table in sequence
  • If you need to access the value of a 64bit local variable in the local variable table, you only need to use an index. (e.g., accessing a long or double variable)
  • If the current frame is created by a constructor or instance method, the object reference to this will be placed in slot with index 0, and the rest of the arguments will be sorted in the argument list.
public class LocalVariablesTest { private int count = 1; // Static methods cannot use this public static voidtestStatic(){// compile error because this variable does not exist in the local variable table of the current method!! System.out.println(this.count); }}Copy the code

2.3.3 Slot reuse

The slots in the local variable table in the stack frame can be reused. If a local variable goes out of its scope, the new local variable declared after its scope is likely to reuse the slots of the expired local variable, so as to achieve the purpose of saving resources.

private void test2() { int a = 0; { int b = 0; b = a+1; } int c = a+1; }Copy the code

2.3.4 Comparison and summary of static variables and local variables

Classification of variables:

  • According to data type:
    • ① Basic data types;
    • ② Reference data type;
  • By position declared in the class:
    • ① Member variables: they all undergo default initialization assignments before they are used
      • Assigning a default value to a class variable during the preparation stage of class loading and linking — assigning an explicit value to a class variable during initialization, i.e. assigning a static code block.
      • Not modified static: Instance variables: As the object is created, instance variable space is allocated in the heap space, with default assignment
    • ② Local variables: before use, must be explicitly assigned! Otherwise, compilation does not pass the supplement:
  • The part of the stack frame that is most relevant for performance tuning is the local variable table. When a method executes, the virtual machine uses a local variable table to complete the method’s delivery
  • Variables in the local variable table are also important garbage collection root nodes, as long as objects referenced directly or indirectly in the local variable table are not collected

2.4 Operand Stack

Stack: This can be implemented using arrays or linked lists

  • Each individual stack frame contains, in addition to the local variable table, a lifO operand stack, also known as an expression stack
  • Operand stack, in which data is written to or extracted from the stack according to bytecode instructions during the execution of a method, i.e. pushed or popped
    • Some bytecode instructions push values onto the operand stack, while others push operands off the stack, use them and push results onto the stack. (e.g., bytecode instruction bipush operation)
    • For example, copy, swap, and sum operations are performed

Against 2.4.1 overview

  • Operand stack, mainly used to store the intermediate results of the calculation process, and as a temporary storage space for variables during the calculation process.
  • The operand stack is a workspace of the JVM’s execution engine. When a method starts executing, a new stack frame is created. The operand stack of this method is empty
  • Each stack of operands has an explicit stack depth for storing values. The maximum depth required is defined by the compiler and stored in the method’s code property as the value of max_stack.
  • Any element in the stack is a Java data type that can be arbitrary
    • 32-bit types occupy one stack unit depth
    • 64-bit types occupy two stack depth units
  • The operand stack does not access the data by accessing the index, but only by pushing and popping the labeled bricks
  • If the called method has a return value, the return value is pushed into the operand stack of the current stack frame and updates the NEXT bytecode instruction to be executed in the PC register.
  • The data types of the elements in the operand stack must exactly match the sequence of bytecode instructions, which is verified by the compiler at compile time and again during the data flow analysis phase of the class validation phase during class loading.
  • In addition, we said Java virtual machineThe interpretation engine is a stack-based execution engine, the stack refers to the operand stack.

    Take a look at the execution of a method (stack frame) in conjunction with the figure below

    1) 15 into the stack; ② Store 15 and 15 into the local variable table

    ③ Press 8; ④ Store 8 and 8 into local variable scale;

(5) Fetch the data with index 1 and 2 from the local variable table and put it on the operand stack; ⑥ IADD operation, 8 and 15 out of the stack

⑦ IADD operation result 23; (8) Store 23 at the position of index 3 in the local variable table

2.4.2 Difference between I ++ and ++ I

2.4.3 ToS (Top-of-Stack Cashing)

  • The zero-address instructions used by stack-based virtual machines are more compact, but more loading and unloading instructions are required to complete an operation, which means more instruction dispatch times and memory read/write times
  • Because operands are stored in memory, frequent memory read/write operations inevitably affect execution speed. In order to solve this problem, the designers of HotSpot JVM have proposed the technology of stack top cache, which caches all the top of stack elements in the CPU registers in the house to reduce the number of reads/writes to memory and improve the execution efficiency of the epidemic

2.5 Dynamic Linking

  • Each stack frame contains an internal reference to the run-time constant pool or to the method to which the stack frame belongs. The purpose of including this reference is to enable dynamic linking in code that supports the current method. Such as invokedynamic instructions
  • When a Java source file is compiled into a bytecode file, all variable and method references are kept in the class file’s constant pool as symbolic Refenrence. For example, describing a method that calls another method is represented by symbolic references to the method in the constant pool, so dynamic linking is used to convert these symbolic references to direct references to the calling method.

A constant pool is used to provide symbols and constants for instruction identification.

2.5.1 Method invocation

** In the JVM, the conversion of symbolic references to direct references to calling methods is related to the method binding mechanism **

  • Static linking When a bytecode file is loaded into the JVM, if the target method being called is known at compile time and the runtime remains the same. The process of converting a symbolic reference to a calling method in this case into a direct reference is called static chaining.
  • Dynamic linking If the invoked method cannot be determined at compile time, that is to say, the symbolic reference of the invoked method can only be converted into a direct reference during the program run time. Because this reference conversion process is dynamic, it is also called dynamic linking.

The Binding mechanism of the corresponding method is: Early Binding and Late Bingding. Binding is the process by which a symbolic reference to a field, method, or class is replaced with a direct reference, which happens only once.

  • Early binding Early binding is invoked if the target method at compile time, and the run-time remains the same, this method can be bound with subordinate type, as a result, due to clearly define the target method is called which one on earth is, therefore, you can use the static link way of converting symbols refer to reference directly.
  • Late binding If the method to be called cannot be determined at compile time, only the related method can be bound according to the actual type at run time, this kind of binding is also called late binding.

As a high-level language, similar to the Java based on object oriented programming language nowadays more and more, even though this type of programming language in grammar has certain difference on the style, but they always maintained a commonality among each other, that’s all support encapsulation, integration and polymorphism of object-oriented features, since this kind of programming languages have polymorphism characteristics, Naturally, there are two types of binding: early binding and late binding. Any ordinary method in Java has the characteristics of virtual functions, which are the equivalent of virtual functions in C++ (which are explicitly defined using the keyword virtual). If you do not want a method to have the characteristics of a virtual function ina Java program, you can mark the method with the keyword final.

2.5.2 Virtual methods and Non-virtual Methods

Subclass object polymorphism using the premise: ① class inheritance relationship ② method rewrite

A virtual method

  • If the version of a method is specified at the compiler, that version is immutable at run time. Such methods are called non-virtual methods
  • Static methods, private methods, final methods, instance constructors, and superclass methods are all non-virtual
  • Other methods are called virtual methods
The virtual machine provides the following method call instructions:

Invokestatic: invokes static methods, and determines the unique method version in the parsing stage; 2. Invokespecial: call the method, private and Frey methods, and determine the unique method version in the analysis stage; 3. Invokevirtual calls all virtual methods; 4. Invokeinterface: Invokes interface methods; 5. Invokedynamic: Dynamically resolve the method to be invoked and execute it. The first four instructions are fixed inside the virtual machine, and the method invocation is performed without human intervention, whereas the InvokeDynamic instruction allows the user to determine the method version. The invokestatic and Invokespecial commands call non-virtual methods, and the rest (excluding final modifications) are virtual methods.

/** * class Father {publicFather(){
        System.out.println("Father default constructor");
    }

    public static void showStatic(String s){
        System.out.println("Father show static"+s);
    }

    public final void showFinal(){
        System.out.println("Father show final");
    }

    public void showCommon(){
        System.out.println("Father show common");
    }

}

public class Son extends Father{
    public Son(){ super(); } public Son(int age){ this(); } public static void main(String[] args) { Son son = new Son(); son.show(); } public static void showStatic(String s){system.out.println (){system.out.println ();"Son show static"+s);
    }

    private void showPrivate(String s){
        System.out.println("Son show private"+s);
    }

    public void show(){
        //invokestatic
        showStatic(Big Head boy);
        //invokestatic
        super.showStatic(Big Head boy);
        //invokespecial
        showPrivate(" hello!"); //invokespecial super.showCommon(); //invokevirtual considers this method non-virtual because it declares that it has final and cannot be overridden by subclasses. //invokevirtual showCommon(); // Not explicitly adding super is considered virtual because subclasses may override showCommon info(); MethodInterfacein= null; In.methoda (); // InvokeInterface is not sure which interface implementation class to override in.methoda (); } public voidinfo(){

    }

}

interface MethodInterface {
    void methodA();
}
Copy the code
About the Invokedynamic instruction
  • The JVM bytecode instruction set was stable until Java 7 added an InvokeDynamic instruction, an improvement Java made for dynamic Typing Language support
  • However, java7 does not provide a way to generate invokedynamic instructions directly. You need to use ASM, the underlying bytecode tool, to generate invokedynamic instructions. It wasn’t until the advent of Java8’s Lambda expressions, the generation of invokedynamic instructions, that direct generation became available in Java
  • The dynamic language type support added in Java7 is essentially a change to the Java virtual machine specification, not to the Java language rules. This is a relatively complex area, and the most immediate benefit of the addition of method calls in the virtual machine is the dynamic language compiler running on Java credentials
Dynamically typed and statically typed languages
  • The difference between a dynamically typed language and a statically typed language is whether the type is checked at compile time or at run time. The former is statically typed and the other is dynamically typed.
  • In plain English static language is to judge the type information of the variable itself; A dynamic type predictor determines the type information of a variable value, which is an important feature of a dynamic language
  • Java is statically typed (although lambda expressions add dynamic features to it), JS, and Python are dynamically typed.

2.5.3 The nature of method rewriting

  • 1 Find the actual type of the object executed by the first element of the operand stack, called C.
  • 2. If a method in type C is found that matches the description in the constant with the simple name, the access permission is checked. If the method passes, the direct reference of the method is returned, and the search process is complete. If not through, it returns the Java. Lang. IllegalAccessError anomalies.
  • 3. Otherwise, search and verify each parent class of C from bottom to top according to the inheritance relationship.
  • 4. If didn’t find the right way, it throws the Java. Lang. AbstractMethodError anomalies. IllegalAccessError describes the application view accessing or modifying a property or calling a method that you do not have permission to access. Normally, this will cause a compiler exception. This error, if it occurs at run time, indicates an incompatible change to a class.

2.5.4 Virtual method table

  • Dynamic dispatch is frequently used in object-oriented programming, and it can affect execution efficiency if you have to re-search through the method metadata for the appropriate target during each dynamic dispatch. Therefore, to improve performance, the JVM implements this by creating a virtual Method table in the method section of the class (non-virtual methods do not appear in the table). Use index tables instead of lookups.
  • Each class has a virtual method table that holds the actual entry to each method.
  • So when is the virtual method table created? The virtual method table is created and initialized during the linking phase of the class load. After the class’s variable initializers are ready, the JVM initializes the class’s party table.

2.6 Method Return Address

  • Holds the value of the PC register that called the method.
  • There are two ways to end a method:
    • Normal Execution Completed
    • Unhandled exception, abnormal exit
  • Either way, the method is returned to where it was called after it exits. When a method exits normally, the value of the caller’s PC counter is returned as the address of the next instruction that calls the method. In the case of an exception exit, the return address is determined by the exception table, which is generally not stored in the stack frame.
  • In essence, the method exit is the process of the current stack frame out of the stack. At this point, it is necessary to restore the local variable table of the upper method, operand stack, return values such as the operand stack of the caller’s stack frame, set PC register values, etc., and let the caller’s method continue to execute.
  • The difference between a normal completion exit and an exception completion exit is that an exception completion exit does not return any value to its upper callers.

When a method is executed, there are only two ways to exit the method: 1. When the execution engine receives a bytecode instruction (return) from any method, the return value will be passed to the upper level method caller, referred to as normal completion exit.

  • Which return instruction a method needs to use after a normal call also depends on the actual data type of the method’s return value
  • In bytecode instructions, the return instructions include iReturn (used when returning values of the types BOOLena, Byte, CHAR, short, and INT), LReturn, Freturn, dreturn, and Areturn, There is also a return directive for methods declared as void, instance initializer methods, class and interface initializer methods

2, in the process of method execution had abnormal (Exception), and the Exception not processed within the method, which is as long as there is no search in this method the Exception table to match the Exception handler, will cause the method exits, referred to as “abnormal complete export methods when an Exception is thrown during the execution of Exception handling, handle exceptions are stored in a table, Easy to find the code to handle exceptions when they occur.

2.7 Additional Information

Stack frames also allow you to carry additional information about the Java virtual machine implementation. For example, support information for program debugging. (Many sources omit additional information.)

2.8 Five interview questions about the VIRTUAL Machine Stack

1. Example stack overflow? (StackOverflowError)

  • Recursive calls, etc., through -xss set stack size;

2. Can stack size be adjusted to prevent overflow?

  • It is not possible to overflow recursively for an infinite number of times, so adjusting the stack size only ensures that the overflow occurs later

3. Is it better to allocate more stack memory?

  • It doesn’t take up space for other threads

4. Does garbage collection involve the virtual machine stack?

  • Don’t
The memory block Error GC
Program counter
Local method stack
JVM virtual machine stack
The heap
Methods area

5. Are local variables defined in methods thread-safe?

  • It should be analyzed on a case-by-case basis
/** * Are local variables defined in methods thread-safe? What is thread-safe? * If only one thread can manipulate this data, the kill is thread-safe. * The data is shared if more than one thread operates on it. There are thread-safety issues if synchronization is not taken into account * * StringBuffers are thread-safe, */ public class StringBuilderTest {//s1 is declared in thread-safe public static voidmethod1(){
        StringBuilder s1 = new StringBuilder();
        s1.append("a");
        s1.append("b"); } //stringBuilder: Public static void method2(StringBuilder StringBuilder){stringBuilder.append("a");
        stringBuilder.append("b"); } public static StringBuilder public static StringBuilder public static StringBuilder public static StringBuildermethod3(){
        StringBuilder s1 = new StringBuilder();
        s1.append("a");
        s1.append("b");
        returns1; } //s1 is thread-safe, StringBuilder toString creates a new String, s1 internally dies public static Stringmethod4(){
        StringBuilder s1 = new StringBuilder();
        s1.append("a");
        s1.append("b");
        return s1.toString();
    }

    public static void main(String[] args) {
        StringBuilder s = new StringBuilder();
        new Thread(()->{
            s.append("a");
            s.append("b"); }).start(); method2(s); }}Copy the code

3 Local method stack

  • The Java virtual machine stack is used to manage the invocation of Java methods, and the local method stack is used to manage the invocation of local methods
  • The local method stack is also thread-private.
  • Allows memory sizes to be implemented as fixed or dynamically scalable. (Same in terms of memory overflow)
    • The Java virtual machine will throw a StackOverFlowError if the thread request allocates more stack capacity than the maximum allowed by the local method stack.
    • The Java virtual machine will throw an OutOfMemoryError if the local method stack can be extended dynamically and there is not enough memory to allocate when trying to extend it, or if there is not enough memory to create the corresponding local method stack when a new thread is created.
  • The native methods are implemented using the C language
  • It is implemented by registering Native methods in the Stack and loading the local Method library at Execution Engine time.
  • When a thread calls a local method, it enters a whole new world that is no longer constrained by the virtual machine. It has the same rights as the VIRTUAL machine
    • Local methods Access the runtime data area inside the virtual machine through the local method interface
    • It can even use the registers in the local processor directly
    • Allocate any amount of memory directly from the heap of local memory
  • Not all JVMS support native methods. Because the Java virtual Machine specification does not specify the language, implementation, data structure, and so on of the native method stack. If the JVM product does not intend to support native methods, you may not need to implement a native method stack.
  • In hotSpot JVM, the local method stack and virtual machine stack are combined directly.



JVM learning code and notes

【 code 】 github.com/willShuhuan… JVM_02 Class loading subsystem JVM_03 Run time data area 1- [program counter + vm stack + local method stack] JVM_04 Local method interface JVM_05 Run time data area 2- heap JVM_06 run time data area 3- Method area JVM_07 JVM_08 Execution Engine JVM_09 String constant pool StringTable JVM_10 Garbage Collection 1- Overview + Related algorithm JVM_11 Garbage Collection 2- Concepts related to garbage collection JVM_12 Garbage collection 3- Garbage collector