温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java是怎么做资源回收补救的

发布时间:2021-11-01 16:06:25 阅读:104 作者:iii 栏目:编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

本篇内容主要讲解“java是怎么做资源回收补救的”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java是怎么做资源回收补救的”吧!

finalize回收

finalize方式是java对象被回收时触发的一个方法。java的很多资源对象,都是在finalize中写了担保的方法。

    /**     * Ensures that the <code>close</code> method of this file input stream is     * called when there are no more references to it.     *     * 
@exception  IOException  if an I/O error occurs.     * 
@see        java.io.FileInputStream#close()     */    protected void finalize() throws IOException {        if ((fd != 
null) &&  (fd != FileDescriptor.in)) {            /* if fd is shared, the references in FileDescriptor             * will ensure that finalizer is only called when             * safe to do so. All references using the fd have             * become unreachable. We can call close()             */            close();        }    }

上面是FileInputStream的finalize方法,在方法被调用时,会检测文件描述符是否存在,如果存在的话就调用close方法。来确保资源的回收。

finalize方法在我们学习java的时候都并不推荐进行重写,也不推荐写复杂的逻辑在里面,主要是因为gc的时候,都会调用这个方法,如果执行的内容太多,就会导致gc被拖长。影响程序的正常运行。而且这里也只是做一个简单的担保。大部分希望的还是编写代码的人可以调用close。这样在做判断的时候就结束了,而不用真正的调用关闭的代码。

Cleaner回收

在DirectByteBuffer中,使用了一个Cleaner对象进行补救的。

          unsafe.setMemory(base, size, (byte) 
0);       
if (pa && (base % ps != 
0)) {           
// Round up to page boundary           address = base + ps - (base & (ps - 1));       } else {           address = base;       }       cleaner = Cleaner.create(this, new Deallocator(base, size, cap));       att = null;

申请完资源后,会创建一个Deallocator对象。

 private static class Deallocator        implements Runnable    {        private static Unsafe unsafe = Unsafe.getUnsafe();        private long address;        private long size;        private int capacity;        private Deallocator(long address, 
long size, 
int capacity) {            assert (address != 
0);            this.address = address;            this.size = size;            this.capacity = capacity;        }        public void run() {            if (address == 
0) {                // Paranoia                return;            }            unsafe.freeMemory(address);            address = 0;            Bits.unreserveMemory(size, capacity);        }    }

Deallocator的run方法中就进行了资源的释放。执行的时机就是靠 Cleaner来触发的。Cleaner是PhantomReference的子类,PhantomReference是Reference的子类。在中有一个ReferenceHandler

    private static class ReferenceHandler extends Thread {

他的run方法就是调用cleaner里的clean方法。这个线程是在静态块里启动起来的。

        Thread handler = 
new ReferenceHandler(tg, 
"Reference Handler");        /* If there were a special system-only priority greater than         * MAX_PRIORITY, it would be used here         */        handler.setPriority(Thread.MAX_PRIORITY);        handler.setDaemon(true);        handler.start();        SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {            @Override            public boolean tryHandlePendingReference() {                return tryHandlePending(false);            }        });

于此同时,并且给SharedSecrets设置了一个JavaLangRefAccess。调用clean方法的过程在tryHandlePending里,这里的参数很重要。

 static boolean tryHandlePending(boolean waitForNotify) {        Reference<Object> r;        Cleaner c;        try {            synchronized (lock) {                if (pending != 
null) {                    r = pending;                    // 'instanceof' might 
throw OutOfMemoryError sometimes                    // so 
do this before un-linking 
'r' from the 
'pending' chain...                    c = r 
instanceof Cleaner ? (Cleaner) r : 
null;                    // unlink 
'r' from 'pending' chain                    pending = r.discovered;                    r.discovered = 
null;                } 
else {                    // The waiting 
on the lock may cause an OutOfMemoryError                    // because it may 
try to allocate exception objects.                    if (waitForNotify) {                        lock.wait();                    }                    // retry 
if waited                    return waitForNotify;                }            }        } 
catch (OutOfMemoryError x) {            // Give other threads CPU time so they hopefully drop some live references            // and GC reclaims some space.            // Also prevent CPU intensive spinning 
in case 
'r instanceof Cleaner' above            // persistently throws OOME 
for some time...            Thread.yield();            // retry            return true;        } 
catch (InterruptedException x) {            // retry            return true;        }

waitForNotify是true的时候,在没有回收对象的时候,会进入阻塞,然后等ooe。外层是个死循环,就会被再次调用到,下次进来的时候就可以出发clean了。ReferenceHandler是管理机制的一种。还有一种就是SharedSecrets调用tryHandlePending(false)。在另外一个类,bits里

    final JavaLangRefAccess jlra = SharedSecrets.getJavaLangRefAccess();        // retry 
while helping enqueue pending Reference objects        // 
which includes executing pending Cleaner(s) 
which includes        // Cleaner(s) that free direct buffer memory        while (jlra.tryHandlePendingReference()) {            if (tryReserveMemory(size, 
cap)) {                return;            }        }

在做reserveMemory的时候,会从SharedSecrets来调用tryHandlePending(false)。这里又变相的进行了一次回收。

到此,相信大家对“java是怎么做资源回收补救的”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:http://blog.itpub.net/69923331/viewspace-2701192/

AI

开发者交流群×