用于自动资源释放的java技术? “提示清理”? [英] java techniques for automatic resource release? "prompt cleanup"?

查看:106
本文介绍了用于自动资源释放的java技术? “提示清理”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向Java移植一些C ++代码,这些代码使用了在堆栈上分配对象的非常常见的C ++技巧(它恰好实现了UDP连接),它具有一些内部状态信息(这里是UDP套接字)。在范围内,该对象用于执行各种操作(发送和接收UDP消息)。好处是当控件离开这个作用域时,对象的析构函数将被运行,这可以指望自动导致释放对象的内部资源(在这种情况下,我确保套接字被关闭,以便我可以重用它的地址和程序其他部分的端口号。)



在试图弄清楚如何做到这一点时,我已经知道Java没有析构函数,那就是敲定不会做我想做的事等等。



肯定有一些同样聪明的技巧可以在Java中完成同样的事情吗?我意识到我可以添加一个close()方法并尝试确保它总是在适当的时候被调用,并且我进一步意识到这可能在Java中比在C ++中更容易和可靠地完成。但是我真的必须走这条路吗?

解决方案

我相信Java 7支持自动资源块管理,这可能是您正在寻找的。

I'm porting to Java some C++ code that uses the pretty common C++ trick of allocating an object on the stack (it happens to implement a UDP connection) which has some internal state information (here, a UDP socket). While in scope the object is used to do various things (send and receive UDP messages). The nice thing is that when control leaves this scope the object's destructor will be run and this can be counted upon to automagically cause the release the object's internal resources (in this case, I make sure the socket gets closed so that I can reuse its address and port numbers in other parts of my program).

In trying to figure out how to do this I have learned that Java does not have a destructor, that "finalize" won't do what I want, etc.

Surely there is some similarly clever technique of accomplishing the same thing in Java? I realize I could add a "close()" method and try to make sure that it is always called at the appropriate time, and I further realize this would probably be more easily and reliably done in Java than in C++. But do I really have to go that route?

解决方案

I believe Java 7 supports Automatic Resource Block Management, which may be what you're looking for.

这篇关于用于自动资源释放的java技术? “提示清理”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆