'Where to close a member variable (e.g.:socket) in a java class?

In my case, the member variable is socket. But this question can be general for any member variable which needs some operations before the object is deleted.

I created a java class "DB" which has a socket member. I create the socket member in constructor.
The socket will keep open until this class "DB" object be GC. Since we should close the socket using "socket.close()" and Java doesn't support destructor. In this case, I wonder where should I put "socket.close()"? Overwrite "finalize()" as below ?

I heard finalize() is deprecated method. Then what will be long term solution for this kind of issue which a member variable need some operation before the object is deleted ?

Thanks.

@Override
protected void finalize() throws IOException 
{
    m_socket.close();
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source