JVM(JVM)

JVM相关面试题

一、GC如何判断对象可以被回收

引用计数法(已被淘汰的算法)

每一个对象有一个引用属性,新增一个引用时加一,引用释放时减一,计数为0的时候可以被回收。但是这种计算方法,有一个致命的问题,无法解决循环引用的问题。(即A引用B,B也引用A,那么对象无法释放)

可达性分析算法(根引用)

1、从GCRoot开始向下搜索,搜索所走过的路径被称为引用链,当一个对象到GCRoot没有任何引用链相连时,则证明此对象是不可用的,那么虚拟机就可以判定回收。

2、那么GCRoot有哪些?

  ①虚拟机栈中引用的对象

  ②方法区中静态属性引用的对象

  ③方法区中常量引用的对象

  ④本地方法栈中(即一般说的native方法)引用的对象

二、不同的引用类型的回收机制

1、强引用:通过关键字new的对象就是强引用对象,强引用对象指向的对象任何时候都不会被回收,宁愿OOM也不会回收

2、软引用:如果一个对象持有软引用,那么当JVM堆空间不足的时候,就会被回收。一个类的软引用可以通过java.lang.ref.SoftReference持有。

3、弱引用:如果一个对象持有弱引用,那么在GC时,只要发现弱引用对象,就会被回收。一个类的弱引用可以通过java.lang.ref.WeakReference持有。

4、虚引用:几乎和没有一样,随时可以被回收。通过PhantomReference持有。

三、JVM的内存模型

根据虚拟机规范,JVM的内存分为堆、虚拟机栈、本地方法栈、程序计数器、方法区5部分。

————————

JVM related interview questions

1、 How does the GC determine that an object can be recycled

< strong > reference counting method (eliminated algorithm) < / strong >

Each object has a reference attribute. Add one when adding a reference, and subtract one when releasing a reference. When the count is 0, it can be recycled. However, this calculation method has a fatal problem, which can not solve the problem of circular reference. (that is, if a references B and B also references a, the object cannot be released)

< strong > reachability analysis algorithm (root reference) < / strong >

1. Starting from gcroot, the search path is called reference chain. When an object is not connected to gcroot by any reference chain, it is proved that the object is unavailable, and the virtual machine can decide to recycle.

2. So what are the gcroot?

① objects referenced in virtual machine stack

② objects referenced by static attributes in the method area

③ objects referenced by constants in the method area

④ objects referenced in the local method stack (i.e. generally speaking, native methods)

2、 Recycling mechanisms for different reference types

1. Strong reference: objects through the keyword new are strong reference objects. The objects pointed to by strong reference objects will not be recycled at any time. You’d rather not recycle oom

2. Soft reference: if an object holds a soft reference, it will be recycled when the JVM heap space is insufficient. The soft reference of a class can be held through java.lang.ref.softreference.

3. Weak reference: if an object holds a weak reference, it will be recycled as long as the weak reference object is found during GC. Weak references to a class can be held through java.lang.ref.weakreference.

4. Virtual reference: almost like nothing, it can be recycled at any time. Held through phantom reference.

3、 Memory model of JVM

According to the virtual machine specification, the memory of the JVM is divided into five parts: heap, virtual machine stack, local method stack, program counter and method area.