Java methods for automatically releasing resources? "prompt cleaning"?

I am porting some C ++ code to Java that uses the fairly common C ++ trick to put an object on the stack (this happens to implement a UDP connection) that has some internal state information (here, a UDP socket). While in scope, an object is used to perform various actions (send and receive UDP messages). The best part is that when the control leaves this area, the destructor object will be launched, and this can be considered automatic output of the object’s internal resources object (in this case, I’m sure that the socket is closed so that I can reuse its address and port numbers in other parts of my program).

In an attempt to figure out how to do this, I found out that Java does not have a destructor, that "finalization" will not do what I want, etc.

Surely there is some similar clever technique for doing the same thing in Java? I understand that I can add the "close ()" method and try to make sure that it is always called at the appropriate time, and I also understand that this will probably be more easily and reliably executed in Java than in C ++. But do I really need to go this route?

+1
java
source share
4 answers

I am sure that Java 7 supports Automatic resource block management , which may be what you are looking for.

+2
source share

You have a {} block in your code that closes the connection and nullifies it. This will make it suitable for garbage collection. That is all you can do.

+1
source share

Java will automatically clear each trigger without a link, as well as the so-called "islands", this is done with automatic garbage collection. You can offer the JVM to gather at any distance, but there is no guarantee that it will fit. The only guatantee is that before the JVM runs out of memory, it will try to clear anything it can.

0
source share

A simple search right here on SO would reveal a lot of questions and answers related to the same topic. I took the liberty of copying some of the more juicy and posting them here.

Is there a C ++ destructor equivalent in Java?

Is there a destructor for Java?

Why doesn't Java have a destructor like C ++?

What is the best way to clean an object in Java?

How do you write a deconstructor in Java?

I am a walking search engine.

-one
source share

All Articles