深入理解Java虚拟机规定下面几种对象可作为GC Roots对象
一开始没反应过来,认为被同步锁持有的对象是被上面几种情况包括的,但是被同步锁持有的对象也可以失去栈或方法区中对其的引用。
如:
public class Main {
volatile static Integer integer = new Integer(1);
static class Node implements Runnable{
Node(){}
@Override
public void run(){
synchronized (integer){
System.out.println(Thread.currentThread().getName()+"locked");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"sleep over");
}
}
}
public static void main(String[] args) throws InterruptedException {
Node node = new Node();
for (int i = 0; i < 2; i++) {
new Thread(node,String.valueOf(i)).start();
TimeUnit.SECONDS.sleep(1);
integer=new Integer(2); //有无此行会影响锁
}
}
}
结果:
这个例子仅仅是说明锁对象的引用更换后,两次integer不是同一把锁。
在被同步锁持有的对象失去所有对它的引用后,逻辑上不应该被垃圾收集器回收,否则被回收后多个等待这个锁的线程怎么办。
转载请注明出处:https://blog.csdn.net/dreambyday/article/details/112299015