java techniques for automatic resource release? "prompt cleanup"? [duplicate]
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 re开发者_如何学编程liably 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.
Have a finally{} block in your code that closes the connection and nulls it. This will make it eligible for garbage collection. Thats all you can do.
Java will automatically clean up everythibg with out a reference, as well as the so called "islands", this is done with automatic garbage collection. You can suggest the JVM to collect at any tine but there is no guarantee that it will comply. The only guatantee is that before the JVM runs out of memory it will try to clean everything it can.
A simple search right here on SO would have revealed a multitude of questions and answers pertaining to the same topic. I took the liberty of copying some of the juicier ones and posting them here.
Is there C++ destructor equivalent in Java?
Is there a destructor for Java?
Why does Java not have any destructor like C++?
What is the best way to clean up an Object in Java?
How do you write a deconstructor in Java?
I'm a walking search engine.
精彩评论