Reputation: 3290
I'm writing a socket interface and would like it's use to look something like this:
SocketServer server = SocketServer.connect("some server url");
server.on("connect", new SocketEvent() {
@Override
public void onEvent() {
"Do something when socket is connected"
}
}
Now what I would like to happen is whenever the variable "server" falls out of scope, the garbage collection will come around and eventually clean in. It's not super vital that it gets freed that instant. I'm trying to avoid something like, server.close();
What I need to know is how I'm to manage the closing of threads and streams under the hood. I've read that finalize gets called when the garbage collector comes around but everybody is saying not to use finalize. Finalize is where I'm thinking I should handle such things but is there a better way?
Upvotes: 1
Views: 497
Reputation: 27125
Finalize is where I'm thinking I should handle such things
Finalizers are called by garbage collection, and the garbage collector runs when there's a need to reclaim unused memory. The garbage collector does not run because of a shortage of file descriptors or database connections or any other resource. It does not run because there's a transaction that's been left hanging open...
Don't use finalize() to close resources. http://www.informit.com/articles/article.aspx?p=1216151&seqNum=7
I'm trying to avoid something like,
server.close();
You can't avoid it. If the library requires you to close() the connection, then you've got to close it.
You can use a try...finally... to guarantee that your resources are closed/cleaned up/whatever:
Server server;
try {
server = ...;
server.foo();
server.bar();
...
} finally {
if (server) {
server.close();
}
}
There's a cleaner way to do it that works in Java7 or Java8 if your resource object implements Closeable:
try(Server server= ...) {
server.foo();
server.bar();
...
}
It's called "try-with-resources", and it means exactly the same as the try...finally... construct above, but the .close() call is implicit.
Upvotes: 2