GC期间未引用的套接字对象

GC期间未引用的套接字对象

本文介绍了GC期间未引用的套接字对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java.util.List对象,它持有连接的套接字用于共享目的。有时候我想刷新这个列表。为此,我将列表大小设置为0.在刷新之前列表中的套接字对象会发生什么情况。在垃圾收集期间,jvm能够正确关闭它们吗?或者我应该自己遍历列表并关闭它们中的每一个? 像 Socket 这些持有OS资源的对象通常会关闭这些资源当收集garabage时(对于套接字,这是在 AbstractPlainSocketImpl )。

但是由于垃圾收集运行时没有定义,您应该自己关闭这些对象以尽早释放这些资源。除此之外,你还有可能花费在操作系统资源上。

编辑:同时阅读Peter Lawrey的评论,他表达了比我能做的更好的理由,为什么等待GC释放OS资源不是一个好主意。


I have a java.util.List object which holds connected sockets for pooling purposes. At some point I want to refresh this list. For this I set list size to 0. What happens to socket objects which were in the list before refresh. Will jvm properly close them during garbage collection ? or should I traverse the list and close each of them by myself ?

解决方案

Objects like Socket which hold OS resources will typically close these resources when garabage collected (for Sockets this is done in the finalizer of AbstractPlainSocketImpl).

But since it is not defined when garbage collection runs you should close such objects yourself to free these resources early. Else you run the risk of exhausting OS resources.

EDIT: also read the comment of Peter Lawrey who expressed it better than I can do why waiting for the GC to free OS resources is not a good idea.

这篇关于GC期间未引用的套接字对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 15:04