要学JVM 垃圾回收机制, 必须先知道什么是GCRoots,根节点, 常见有
这里解释第一栈变量, 理解为就是main 方法中, 中的变量,
public static void main(String[] args) {
// Root Var
User userA = new User();
userA.setName("GC Root A");
User userB = new User();
userB.setName("GC Root B");
{
User userC = new User();
userC.setName("GC Root C");
}
f1();
while (true) {
userA.hashCode();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void f1() {
User NodeA = new User();
NodeA.setName("Node A");
}
}
public static void main(String[] args) {
// Root Var
User userA = new User();
userA.setName("GC Root A");
User userB = new User();
userB.setName("GC Root B");
{
User userC = new User();
userC.setName("GC Root C");
}
f1(userB);
while (true) {
userA.hashCode();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void f1(User root) {
User NodeA = new User();
NodeA.setName(root.getName() + ", Child Node A");
root.save(NodeA);
}
可以看到 Node A 活下来了