A JVM

Alert ourselves to learn and grow

1. Common interview questions

  1. Please talk about your understanding of the jvm? Java8 what's new virtual machine,

    jvm is the basis for cross-platform Java, it runs the JVM time zone data, execution engine, local library interface, consisting of native method libraries

  2. What is the OOM, you talk about the reasons OOM generated? How to analyze

    OOM: OutOfMemoryError, out of memory when the JVM because there is not enough memory to allocate space for the object and the garbage collector has no spatial recyclable, it will throw this ERROR.

    Causes:

    • Virtual machine memory is not enough:
      • The current size of the application memory footprint server, you can try to transfer large virtual machine memory test.
    • Out of memory / memory leak
      • Parameters can be added when the program is running, Dump memory snapshot is generated for analysis when there is a memory overflow.
  3. Jvm tuning parameters used in which

    -Xmx: set the maximum heap

    -Xms: Set the minimum stack

    ...

  4. Memory snapshot, analyze how to crawl, what command?

    Use -XX: + HeapDumpOnOutOfMemoryError command set is generated OOM abnormality memory snapshot

  5. Heap inside partition: Eden, Survial (from to), tenured

  6. GC garbage collection algorithms and which of? To talk about the pros and cons

  7. How to determine when jvm garbage collection garbage, GCRoots

  8. -x -xx parameters which you used

  9. jvm tuning parameters been your favorite project configuration after release

  10. References, strong references, weak references, phantom references are what you talk about

  11. The relationship between GC and GC garbage collector algorithm? What are?

  12. G1 garbage collector characteristics

  13. OOM seen several

java -XX:+PrintCommandLineFlags -version

C:\Users\tianxc>java -XX:+PrintCommandLineFlags -version
-XX:InitialHeapSize=266536512 -XX:MaxHeapSize=4264584192 -XX:+PrintCommandLineFlags -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:-UseLargePagesIndividualAllocation -XX:+UseParallelGC
java version "1.8.0_191"
Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

2.JVM location

3.JVM architecture

Our so-called tuning is in tune heap

4. The class loader

Loading a class, the connection and initialization

Load: find and load the class of binary data

connection:

  • Verify: ensure the correctness of the loaded class
  • Preparation: static variables to allocate memory space for the class, assign a default initial value
  • Analysis: The class is converted into direct reference symbol references

When compiled to the Java class files, virtual machine does not know the address referenced by the mnemonic: symbolic references! Into a direct reference to the real, direct address to find corresponding.

Initialization: Static variables assigned to the class of the correct value.

public class Test{
    public static int a=1;
}
//1.加载 编译文件为.class文件,通过类加载,加载到JVM

//2.连接
//验证(1) 保证class类文件没有问题
//准备(2) 给int类型分配内存空间,a=0;
//解析(3) 符号引用转换为直接引用。

//3.初始化
//经过这个阶段的解析,把1赋值给变量a

Load static class

package com.ruyidd.classloader;

/**
 * @author: tianxc
 * @date: 2020-03-10 15:13
 * @desc: JVM参数:-XX:+PrintGCDetails//打印GC垃圾回收信息
 * -XX:+TraceClassLoading 打印类加载信息
 * rt.jar   jdk出厂自带的,最高级别的类加载器要加载的。
 */
public class Demo01 {

    public static void main(String[] args) {
        System.out.println(MyChild01.str2);
    }
}
class Myparent01{

    private static String str = "hello,world";
    static {
        System.out.println("Myparent01 static");
    }

}
class MyChild01 extends Myparent01{
    public static String str2 = "hello,str2";
    static {
        System.out.println("MyChild1 static");
    }
}

final constants at compile time when he put in a constant pool:

This will put the code constants of the constant pool Demo02, after Demo02 and MyParent02 it does not matter

package com.ruyidd.classloader;

/**
 * @author: tianxc
 * @date: 2020-03-10 16:55
 * @desc:
 */
public class Demo02 {
    public static void main(String[] args) {
        //直接从常量池中获取
        System.out.println(MyParent02.str);
    }

}
class MyParent02{
    public static final String str = "hello world";
//
    static {
        System.out.println("MyParent02 static");
    }
}

package com.ruyidd.classloader;

import java.util.UUID;

/**
 * @desc: 当一个常量的值并非编译的期间可以确定的,
 * 那这个值就不会被放入方法调用类的常量池中
 * 程序运行期间的时候,会主动使用常量所在的类
 */
public class Demo03 {

    public static void main(String[] args) {
        System.out.println(MyParent03.str);
    }
}

class MyParent03{
    public static final String str = UUID.randomUUID().toString();

    static {
        System.out.println("MyParent03 static");
    }
}

ClassLoader classification

  1. Java Virtual Machine that comes with loader
    • BootStrap root loader (for loading system, JDK classes in the core library rt.jar)
    • Ext extension class loader (extended load some jar package class)
    • Sys / App system (application class) loader (write our own classes)
  2. User-defined loader
    • ClassLoader, only need to extend this abstract class can define your own class loader

package com.ruyidd.classloader;

/**
 * @author: tianxc
 * @date: 2020-03-10 17:17
 * @desc:
 */
public class Demo04 {

    public static void main(String[] args) {
        Object o = new Object();
        Demo04 demo04 = new Demo04();
//null 在这里并不代表没有,只是Java触及不到
        System.out.println(o.getClass().getClassLoader());//null
        System.out.println(demo04.getClass().getClassLoader());//sun.misc.Launcher$AppClassLoader@18b4aac2


        System.out.println(demo04.getClass().getClassLoader().getParent());//sun.misc.Launcher$ExtClassLoader@1b6d3586
        System.out.println(demo04.getClass().getClassLoader().getParent().getParent());//null


    }
}

Parents appoint mechanisms: one level so that the parent class to load, if the top of the loader can not load, and then so on down.

Parents delegate mechanism to protect the core Java classes will not be replaced by their own definition of the class

5.native: local method

native: As long as this is with keyword, indicating the scope of Java not only to call the underlying C language library

Robot class

JNI: Java Native Integer (Java native method interface)

6. Program Counter

Each thread has a program counter, thread private.

The program counter is a very small memory space :( almost negligible)

Action: The current line number indicator bytecode execution.

bipushThe int, float, String, pushed to the stack constant value;

istore Storing a value from operand stack into local variables table

iaddplus

imul Multiply

7. The method area

Method Area method area is one of the runtime data area Java Virtual Machine Specification defined, and heap (Heap), as can be shared between threads

Before JDK1.7

Permanent Generation: used to store some of the virtual machine to load class information, constants, strings and static variables. These things will put a permanent generation; the size of the permanent generation space is limited: if full: OutOfMemoryError: PermGen

JDK1.8

(HotSpot jvm jdk1.8 at the time) would perpetual generations removed completely, Java Heap or Metaspace (Native Heap) element space

Yuan is the way to achieve space area in the HotSpot jvm

The method is mainly to save area: class information, constants, a string, a static variable, a reference symbol, the method code

Generation and permanent dimensional space are achieved jvm zone specification method.

Yuan and permanent space on behalf biggest difference: dimensional space is not in the Java virtual machine, using a local memory.

-XX:MetaspaceSize10m

If the yuan space is full: OutOfMemoryError: MetaSpace

8. Stack (Stack)

Stacks and queues (stacks and queues are the basic data structure.)

Stacks and queues are the basic data structure:

The program is running is actually push the process.

The stack is empty, the thread is over.

What is Stack Stack

Run-time stack is the management program

Some basic types of reference values ​​stored objects, methods and the like. . .

Stack advantages: access speed faster than the reactor, after register, stack data can not be shared.

StackOverflowError stack overflow

public class Demo01 {

    public static void main(String[] args) {
        a();
    }
//Exception in thread "main" java.lang.StackOverflowError
    private static void a(){
        a();
    }
}

Stack which is certainly not a problem of garbage collection, as long as the thread Once finished, the stack is over, life cycle and thread consistency.

Stack principle

Constituent elements of Java stack: the stack frame

Stack (What deposit?) + + Heap interaction diagram method area

Stack deposit: local variable table, the basic types of data (int, double ...), object references, method of indexing ...

This is our main stack HotSpot (pointer)

3 JVM:

  • SUN's HotSpot
  • BEA's JRockit
  • IBM's J9VM

9. heap (Heap)

Java7 before:

Heap stack, a heap jvm only one example, the size of the memory is adjustable.

You can save content: classes, methods, constants, holds true type of reference information.

Divided into three parts:

  • Neonatal region: Young (Eden-s0-s1)
  • Pension District: Old Tenure
  • Permanent Area: Perm

Heap memory logically divided into three parts: newborn, pension, permanent (hereinafter called element space JDK1.8)

Only physically newborn, pension; element in the local memory space, not in the JVM.

GC garbage collection mainly in the young generation and pension area, is divided into ordinary GC and Full GC, if filled, will burst OutOfMemoryError

Young generation

The young generation is a class of birth, growth demise of place

The young generation segments: Eden, S0, S1 (from, to), all classes have been out in the new Eden, Eden slowly when full, the program also need to create an object and they will trigger a lightweight GC; cleaned after a garbage objects will survive, we will put the survivors zone (s0, s1); after cleanup 15 times, there have been some extremely tenacious objects, some objects break through the garbage 15 times after that, this time will be the object into the pension area, running for a few months, the pension area is full, it will trigger a full GC; if the entire space will totally full, on the OOM.

Sun HotSpot virtual machine, memory management (generational management mechanism, different regions use different algorithms.)

Eden from to

Pension area

15 objects have survived into the pension area, after the pension area is full, trigger Full GC

The default is 15 times, can be modified

Permanent region (Perm)

JDK put some carry their own Class, the metadata Integer

Hardly garbage collection:

OutOfMemoryError: PermGen when the project started permanent behalf not enough: It is possible to load a large number of third-party packages.

Before jdk1.6: permanent generation method in the constant pool area

jdk1.7: permanent behalf, but he began to try to permanently generations, constant pool in the heap

jdk1.8: no generation of permanent, replaced membered space; constant pool in the element space.

Method and heap region, is a shared area, is a logical part of the JVM specification, also referred to him as non-heap

Dimensional space: a local memory

10. The heap memory tuning (initial)

Adjust a test:

package com.ruyidd.heap;

/**
 * 默认情况
 * maxMemory=3791650816(字节) 3616.0MB(虚拟机试图使用的最大的内存 一般是物理内存的1/4)
 * totalMemory=257425408(字节)    245.5MB(虚拟机默认初始内存总量 一般是物理内存的1/64)
 *
 * 我们可以自定义堆内存的总量:
 * -XX:+PrintGCDetails;//输出详细的垃圾回收信息
 * -Xmx:最大分配内存 1/4
 * -Xms:初始分配的内存大小1/64
 * -Xmx1024m -Xms1024m -XX:+PrintGCDetails
 */
public class Demo01 {

    public static void main(String[] args) {
        //获取堆内存的初始大小和最大大小
        long maxMemory = Runtime.getRuntime().maxMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();
        System.out.println("maxMemory="+maxMemory+"(字节)\t"+(maxMemory/1024/(double)1024)+"MB");
        System.out.println("totalMemory="+totalMemory+"(字节)\t"+(totalMemory/1024/(double)1024)+"MB");
    }
}

Test two: OOM

package com.ruyidd.heap;

import java.util.Random;

/**
 * -Xmx8m -Xms8m -XX:+PrintGCDetails
 *
 * [GC (Allocation Failure) [PSYoungGen: 1536K->488K(2048K)] 1536K->640K(7680K), 0.0009800 secs] [Times: user=0.05 sys=0.00, real=0.00 secs]
 * [Full GC (Ergonomics) [PSYoungGen: 1981K->0K(2048K)] [ParOldGen: 4775K->2733K(5632K)] 6757K->2733K(7680K), [Metaspace: 3204K->3204K(1056768K)], 0.0039491 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
 * 1. GC类型:GC——普通GC;Full GC——重GC
 * 2. 1536K 执行GC之前的大小
 * 3. 488K 执行GC之后的大小
 * 4. (7680K) young 的total大小
 * 5. 0.0009800 secs清理的时间
 * 6. user 总计GC所占用CPU的时间  sys os调用等待的时间 real 应用暂停的时间
 *
 * GC的执行方式:串行执行STW(stop The World);并行执行:G1
 */
public class Demo02 {

    public static void main(String[] args) {
        String str = "lkasjdflkajlfkjakdjfalkdsfj";
        while (true){
            str += str
                    + new Random().nextInt(999999999)
                    + new Random().nextInt(999999999);
        }
        //出现的问题 java.lang.OutOfMemoryError: Java heap space
    }
}

11.Dump memory snapshot

View tool:

  1. Jconsole
  2. Eclipse(MAT)
  3. Idea (Jprofile plug-in)

Jprofile plug

Fast Experience

Guess you like

Origin www.cnblogs.com/tianxc/p/12459660.html
JVM
JVM