JVM | How Java programs perform

Source: Internet
Author: User

  • class file Structure Basics
  • A class file is a set of binary streams that are based on 8-byte units, and each data item is arranged in a compact order in the class file, with no delimiters in the middle.
    There are only two data types in the class file storage structure: Unsigned numbers and tables (tables are also composed of multiple unsigned numbers or other tables). Unsigned numbers are basic data types that represent 1-byte, 2-byte, 4-byte, 8-byte unsigned numbers, respectively, in U1, U2, U4, and U8. The unsigned number is the cornerstone of the class file.

      • Bytecode Instruction Basics

    Reference: http://blog.51cto.com/damon188/2131035

      • Review JVM Runtime data regions

      • Method Area:

    Thread sharing, which stores the class information, constants, static variables, and immediate compiler-compiled code that have been loaded by the virtual machine.

      • Heap:

    Thread sharing, storing object instances.

      • Program Counter:

    Thread-Private, which stores the offset address (instruction line number) of the virtual machine bytecode instruction that the current thread is executing.

      • Virtual Machine Stack:

    Thread-Private, describing the memory model that the Java method executes.

      • The memory model that the method executes

      • Local Variables Table:

    Variable storage space, storing the method parameters, the local variables defined within the method.

      • Operand stack:

    Execution of the space, the execution of the process, there will be a variety of bytecode instruction network operations to write and extract the content, into the stack, the stack operation.

      • Dynamic Connection:

    Each stack frame contains a reference to the method that the stack frame belongs to in the running constant pool.
    A symbol reference that is converted to a direct reference during each run.
    The conversion process is referred to as a direct reference to a symbolic reference when the class is loaded or used for the first time, and is called static parsing.

      • Return Address:

    The location where the method is called.

      • Local variable table slot slot multiplexing problem:

        public class Slotreuse {
        public static void MethodA () {
        byte[] placeholder = new byte[64 1024x768 1024];
        System.GC ();
        }
        public static void MethodB () {
        {
        byte[] placeholder = new byte[64 1024x768 1024];
        }
        System.GC ();
        }
        public static void Methodc () {
        {
        byte[] placeholder = new byte[64 1024x768 1024];
        }
        int a = 0;
        System.GC ();
        }
        public static void Main (string[] args) {
        MethodA ();
        MethodB ();
        METHODC ();
        }
        }

    Virtual machine run parameters Plus "-VERBOSE:GC" to view the garbage collection process.

    • Executive MethodA ();
    [GC 69499K->66048K(251392K), 0.0010970 secs][Full GC 66048K->65866K(251392K), 0.0098170 secs]

    In the scope of variable placeholder, do not dare to reclaim placeholder memory.

    • Executive MethodB ();
    [GC 69499K->66048K(251392K), 0.0011820 secs][Full GC 66048K->65866K(251392K), 0.0112650 secs]

    Logically out of the scope of the placeholder, placeholder's memory is still not recycled, because after leaving the scope of the placeholder, there is no read and write operations on the local variable table, The slot slots originally occupied by placeholder have not been reused by other variables, and the local variable table that is part of the GC roots remains associated with it.

    • Executive METHODC ();
    [GC 69499K->66000K(251392K), 0.0012780 secs][Full GC 66000K->330K(251392K), 0.0099390 secs]

    The slot slot used by placeholder was reused by other variables, cutting off GC Roots Association and normal garbage collection.

      • How to find the right way

    Determining the version of the called method (that is, which method is called) is the only task in the method invocation phase.

      • 5 Methods Call bytecode directives:

    1) invokestatic: Call the static method.
    2) Invokespecial: Invokes the instance constructor <init> method, private method, and parent class method.
    3) Invokevirtual: All virtual methods are called. Non-virtual methods are virtual, and non-virtual methods include methods that use Invokestatic, Invokespecial calls, and final-modified methods.
    4) Invokeinterface: Invokes the interface method, and the runtime then determines an object that implements this interface.
    5) Invokedynamic: Used to dynamically parse the method referenced by the call Point qualifier at run time and execute the method.
    Ireturn (return value is Boolean, Byte, char, short, int), Lreturn, Freturn, Dreturn, Areturn: Method return instruction.

      • Static parsing

    Method has a deterministic version of the call before the program actually runs, and the call version is immutable at run time.
    As long as the method can be called by the invokestatic and invokespecial instructions, it is possible to determine the unique invocation version in the parsing phase, which has a static method, a private method, an instance constructor, and a parent class Method 4 class.

    public class StaticResolution {            public static void sayHello(){                    System.out.println("hello world");            }            public static void main(String[] args) {                    sayHello();            } }

    BYTE code:

    public static void main(java.lang.String[]);         Signature: ([Ljava/lang/String;)V         flags: ACC_PUBLIC, ACC_STATIC         Code:             stack=0, locals=1, args_size=1             0: invokestatic  #5                  // Method sayHello:()V             3: return         LineNumberTable:             line 14: 0             line 15: 3
      • Static Dispatch

    All dependent static types are used to locate the dispatch action of the method execution version.
    Dispatch opportunity: Compile phase
    Typical application: Method overloading
    e.g.

     public class Staticdispatch {public static void SayHello (short arg) {System.out.println (" Hello short "); } public static void SayHello (Byte arg) {System.out.println ("Hello byte"); } public static void SayHello (object arg) {System.out.println ("Hello Object"); } public static void SayHello (int arg) {System.out.println ("Hello int"); } public static void SayHello (Long arg) {System.out.println ("Hello Long"); } public static void SayHello (char arg) {System.out.println ("Hello char"); } public static void SayHello (char ... args) {System.out.println ("Hello char ..."); } public static void SayHello (Serializable arg) {System.out.println ("Hello Serializable"); } public static void Main (string[] args) {SayHello (' a '); }}

    The current main method compiles a byte code:

    public static void main(java.lang.String[]);Signature: ([Ljava/lang/String;)Vflags: ACC_PUBLIC, ACC_STATICCode:  stack=1, locals=1, args_size=1     0: bipush        97     2: invokestatic  #12                 // Method sayHello:(C)V     5: return  LineNumberTable:    line 46: 0    line 47: 5

    Note the public static void SayHello (char arg) constructs a method after the bytecode is compiled:

    public static void main(java.lang.String[]);Signature: ([Ljava/lang/String;)Vflags: ACC_PUBLIC, ACC_STATICCode:  stack=1, locals=1, args_size=1     0: bipush        97     2: invokestatic  #11                 // Method sayHello:(I)V     5: return  LineNumberTable:    line 46: 0    line 47: 5

    (Variable long character)
    It can be wide and not narrow.

      • Dynamic Dispatch

    The run period determines how the version's dispatch action is performed based on the actual type.
    Dispatch Time: Run phase
    Typical application: Method overrides
    e.g.

        public class DynamicDispatch {            static abstract class Human {                    protected abstract void sayHello();            }            static class Man extends Human {                    @Override                    protected void sayHello() {                            System.out.println("man say hello");                    }            }            static class Woman extends Human {                    @Override                    protected void sayHello() {                            System.out.println("woman say hello");                    }            }            public static void main(String[] args) {                    Human man = new Man();                    Human woman = new Woman();                    man.sayHello();                    woman.sayHello();                    man = new Woman();                    man.sayHello();            }    }

    BYTE code:

        public static void Main (java.lang.string[]); Signature: ([ljava/lang/string;) V flags:acc_public, Acc_static code:stack=2, locals=3, Args_siz                 e=1 0:new #2//Class Edu/atlas/demo/java/jvm/dynamicdispatch$man 3:dup 4:invokespecial #3//Method Edu/atlas/demo/java/jvm/dynamicdispatch$man. " <init>:() V 7:astore_1 8:new #4//Class Edu/atlas/demo /java/jvm/dynamicdispatch$woman 11:dup 12:invokespecial #5//Method edu/ Atlas/demo/java/jvm/dynamicdispatch$woman. "                  <init> ":() V 15:astore_2 16:aload_1 17:invokevirtual #6 Method Edu/atlas/demo/java/jvm/dynamicdispatch$human.sayhello: () V 20:aload_2 21:INV Okevirtual #6//Method Edu/atlas/demo/java/jvm/dynamicdispatch$human.sayhello: () V 24:new #4//Class edu/atlas/ Demo/java/jvm/dynamicdispatch$woman 27:dup 28:invokespecial #5//Method Edu/atlas/demo/java/jvm/dynamicdispatch$woman. "                  <init> ":() V 31:astore_1 32:aload_1 33:invokevirtual #6 Method Edu/atlas/demo/java/jvm/dynamicdispatch$human.sayhello: () V 36:return Linenumberta                Ble:line 32:0 line 33:8 line 34:16 line 35:20 Line 36:24 line 37:32 line 38:36
    • The run-time parsing process for invokevirtual directives:
      1) Find the actual type of the object pointed to by the first element at the top of the operand stack, as C.
      2) If you find a method in type C that is equal to both the descriptor and the simple name in the constant, the access check is performed,
      If passing returns the direct reference to this method, the lookup process is completed;
      Returns the Java.lang.IllegalAccessError exception if it does not pass.
      3) Otherwise, follow the inheritance relationship from the bottom up to the 2nd step of the search and validation process for each parent class C.
      4) If the appropriate method is not always found, throw the Java.lang.AbstractMethodError exception.

    Since the first step of the invokevirtual instruction is to determine the world type of the receiver during run time, the invokevirtual instruction of the two calls resolves the class method symbol reference in the constant pool to a different direct reference, which is the essence of the Java language method rewrite.

      • Implementation of dynamic dispatch of virtual machine

    The process of dynamic dispatch is described above, however, due to the fact that dynamic dispatch is a very frequent action, the actual implementation of virtual machines is based on performance considerations, and most implementations do not really carry out such frequent searches. The commonly used stability optimization method is to establish a virtual method table (vtable) for the class in the method area, and interface method to establish the interface Method table (itable).
    The virtual method table holds the actual entry address for each method.
    If a method is not overridden in a subclass, then the address of the virtual method inside the subclass and the address entry for the same method as the parent class are consistent, pointing to the implementation portal of the parent class side.
    If this method is overridden in a subclass, the address in the subclass method table will be replaced with the entry address that points to the subclass implementation version.
    The method table is typically initialized at the connection stage of the class load, and after the class's variable initial value is prepared, the virtual opportunity initializes the method table for that class.

      • How to execute bytecode within a method
    • Stack-based interpreter execution process
      e.g.
    public static int methodA(int a, int b){    return a + b;}public static int methodB(int a, int b){    return a - b;}public static int methodC(int a, int b){    return a * b;}public static int heavyMethod(){    int a = 200;    int b = 100;    int c = methodC(methodA(a, b), methodB(a, b));    return c;}

    BYTE code:

        public static int MethodA (int, int);                 Signature: (II) I flags:acc_public, Acc_static code:stack=2, locals=2, args_size=2                0:iload_0 1:iload_1 2:iadd 3:ireturn linenumbertable:        Line 18:0 public static int MethodB (int, int);                 Signature: (II) I flags:acc_public, Acc_static code:stack=2, locals=2, args_size=2                0:iload_0 1:iload_1 2:isub 3:ireturn linenumbertable:        Line 22:0 public static int methodc (int, int);                 Signature: (II) I flags:acc_public, Acc_static code:stack=2, locals=2, args_size=2                0:iload_0 1:iload_1 2:imul 3:ireturn linenumbertable:        Line 26:0 public static int Heavymethod (); Signature:() I flags:acc_public, Acc_static code:stack=3, locals=3, args_size=0 0:sipush  3:istore_0 4:bipush 6:istore_1 7:                Iload_0 8:iload_1 9:invokestatic #17//Method MethodA: (II) I                12:iload_0 13:iload_1 14:invokestatic #18//Method MethodB: (II) I 17:invokestatic #19//Method METHODC: (II) I 20:istore_2 21                : iload_2 22:ireturn linenumbertable:line 128:0 line 129:4 Line 130:7 Line 140:21

    Legend Analysis:

    JVM | How Java programs perform

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.