Java垃圾回收机制之常见GC面试题

mac2025-08-08  17

GC相关面试题

Object的finalize()方法的作用是否与C++的析构函数的作用相同 ++与C++的析构函数不同,析构函数调用确定,而它的是不确定的 ++将未被引用的对象放置于F-Queue队列 ++方法执行随时可能被终止 ++给予对象最后一次重生的机会

package com.huke.gc; public class Finalization { public static Finalization finalization; protected void finalize(){ System.out.println("Finalized"); finalization = this; } public static void main(String[] args) { Finalization f = new Finalization(); System.out.println("First print"+f); f = null; System.gc(); try{//休息一段时间让上面的垃圾回收线程执行完成 Thread.currentThread().sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("Second print:" + f); System.out.println(f.finalization); } }

Java中的强引用,软引用,弱引用,虚引用有什么用

强引用(Strong Reference) ++最普遍的引用:Object obj = new Object() ++抛出OutOfMemoryError终止程序也不会回收具有强引用的对象 ++通过对象设置为null来弱化引用,使其被回收

软引用(Soft Reference) ++对象储在有用但非必须的状态 ++只有当内存空间不足时,GC会回收该引用的对象的内存 ++可以用来实现高速缓存 String str = new String(“abc”);//强引用 SoftReference softRef = new SoftReference(str);//软引用

最新回复(0)