Java使用finalize为另一个线程添加清理任务

时间:2016-09-07 06:39:08

标签: java finalize resource-management

我在Java中使用OpenGL,我必须删除外部资源(如vbos)。建议的方法是使用Disposable接口。但是这样做需要我几乎每个处理资源的类都实现这个接口。我已经尝试过了,但我常常不清楚哪个对象应该负责调用dispose()方法。这就是为什么我编写这样的东西:

public abstract class Destroyable {
    private static final ArrayList<Runnable> cleanupTasks = new ArrayList<Runnable>();

    public static void cleanup() {
        synchronized (cleanupTasks) {
            for (Runnable cleanupTask : cleanupTasks) {
                cleanupTask.run();
            }
        }
    }

    protected abstract void destroy();

    @Override
    protected void finalize() throws Throwable {
        try {
            synchronized (cleanupTasks) {
                // Let's do cleanup in the main thread as the garbage collector runs in another thread
                cleanupTasks.add(new Runnable() {
                    public void run() {
                        destroy();
                    }
                });
            }
        } finally {
            super.finalize();
        }
    }
}

由于垃圾收集器大部分时间都不会运行,我每五秒钟就会调用Destroyable.cleanup()System.gc()

如果某些资源最终没有被破坏(就像静态资源一样)并不是那么糟糕,因为我在最后删除了上下文(这也破坏了其他资源)。

这是一个好主意还是有更好的方法来做到这一点?

0 个答案:

没有答案