13 Jun 2012 10:38
GC closes my ServerSocket
Hi All
I have a test that basically looks like:
int p = new ServerSocket(0).getLocalPort();
//....
new Socket("localhost", p);
Recently it's failing on solaris-i586, and after some investigation, I
realize that the ServerSocket object is GC'ed and auto-closed.
(But why only recently?)
So I change the first line to
ServerSocket ss = new ServerSocket(0);
int p = ss.getLocalPort();
and it's running fine.
I want to know if the ServerSocket object still has a chance to be
closed. If yes, I'll add a
ss.close();
at the end to be safer.
Thanks
Max
(Continue reading)
> Noreg-self.
>
> *Chris*: I didn't indented the whole test by wrapping them into a
> try-finally (or try-with-resources) block. The test runs in othervm and
> I guess the sockets will be closed anyway.
Strictly speaking, after the construction of these ServerSocket instance
you should wrap the remainder of the code in a try finally to ensure
that close is called. Even with othervm mode when the vm is exiting
there is not guarantee that finalizers are run.
I think it would be best to add a finally block here to reduce the
chances of strange/intermittent behavior as a result of running this
test. Either the test itself or excessive resource hogging on the
system. But if you are really against it, I can live with what you have
)
RSS Feed