2:finalize机制可能会导致性能问题,死锁和线程挂起。
3:finalize中的错误可能导致内存泄漏;如果不在需要时,也没有办法取消垃圾回收;并且没有指定不同执行finalize对象的执行顺序。此外,没有办法保证finlize的执行时间。
遇到这些情况,对象调用finalize方法只有被无限期延后
class User{ public static User user = null; @Override protected void finalize() throws Throwable { System.out.println("User-->finalize()"); user = this; } } public class FinalizerTest { public static void main(String[] args) throws InterruptedException { User user = new User(); user = null; System.gc(); Thread.sleep(1000); user = User.user; System.out.println(user != null);//true user = null; System.gc(); Thread.sleep(1000); System.out.println(user != null);//false } }
public class Finalizer { @Override protected void finalize() throws Throwable { System.out.println("Finalizer-->finalize()"); } public static void main(String[] args) { Finalizer f = new Finalizer(); f = null; System.gc();//手动请求gc } } //输出 Finalizer-->finalize()
在Java9 以后 提供了最终类Clear来代替实现,下面看一下官方例子
package Thread; import java.lang.ref.Cleaner; public class CleaningExample implements AutoCloseable{ private final static Cleaner CLEANER=Cleaner.create();// 创建者模式创建对象 static class State implements Runnable{ // 清理对象 下面说 State() { System.out.println("init"); } @Override public void run() { System.out.println("close"); } } private final State state; private final Cleaner.Cleanable cleanable; // clearner 中的接口 实现唯一的清理方法 public CleaningExample() { super(); this.state = new State(); this.cleanable=CLEANER.register(this, state); // 注册清理容器中 并且需要清理对象的引用 } @Override public void close() throws Exception { cleanable.clean(); //进行清理操作 } public static void main(String[] args) { while(true) { new CleaningExample(); } } }
上面 看出:
static class State implements Runnable
* 1. 注册的Object处于幻象引用状态
public class CleaningExample extends Thread implements AutoCloseable { private final static Cleaner CLEANER = Cleaner.create(); private final State state; private final Cleaner.Cleanable cleanable; public CleaningExample() { this.state = new State(); this.cleanable = CLEANER.register(this, state); } @Override public void close() throws Exception { cleanable.clean(); } @SuppressWarnings("resource") public static void main(String[] args) { while (true) { CleaningExample example = new CleaningExample(); } } // 模拟业务请求 @Override public void run() { System.out.println("数据库 海量 查询请求 ................"); } // 清理模版 class State implements Runnable { State() { System.out.println("<--- init --->"); } @Override public void run() { System.out.println("<--- close --->"); } } }
/** * Heads of a CleanableList for each reference type. */ final PhantomCleanable<?> phantomCleanableList; final WeakCleanable<?> weakCleanableList; final SoftCleanable<?> softCleanableList; // The ReferenceQueue of pending cleaning actions final ReferenceQueue<Object> queue;
在CleanerImpl 类进行clearner类的最终实现,看以看到定义的这些个字段,基本上明确了 他的基本原理