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?
java
Daniel Chisholm
source share