views:

171

answers:

1

In Java:

I have an object that holds references to 2 daemon threads. I am considering the corner case where it is not deinitialized, so I can determine whether I need a finalizer. The function for detinitializing stops the threads. I could go ahead and just add a finalizer but I am curious:

a) Can the object get garbage collected while the above threads are alive?

b) If it can get garbage collected, will the threads get interrupted?

+1  A: 

You should not stop threads on finalization, because
One should not make behavior of the application dependent on garbage collection.

Garbage collection is very in-deterministic:

  • Different JVMs,
  • different JVM switches,
  • different operating systems,
  • different hardware architectures,
  • different hardware specifics (CPU, cores, memory)...

Everything affects garbage collection.

So, just rethink your concept, and give us more information, why a thread should be stopped and when.

ivan_ivanovich_ivanoff
Well, in the normal case the user would properly disconnect() -- and the threads (which deal with I/O) would be stopped. I was considering the case where the disconnection is not done properly.
shikhar
Then you should go with, let me think, ... keepalive checks? After a timeout of "no response" the thread is killed. Because this would be very deterministic, compared to GC.
ivan_ivanovich_ivanoff
can you elaborate? "no response" from? btw, here is the code: http://code.google.com/p/commons-net-ssh/source/browse/src/main/java/org/apache/commons/net/ssh/trans/Transport.java#80
shikhar
Is it typical for such scenario: You have client sockets, you send them keep-alive requests, they respond to it. When one socket don't respond, well, it's disconnected.
ivan_ivanovich_ivanoff
Of course you would need an extra thread for each connection to do keepalives. This makes the whole thing more complicated, but well, that's network programming.
ivan_ivanovich_ivanoff
I should have mentioned that it is a client-side code, and a library at that -- by user calling disconnect() I meant the API user :-) -- so could you reevaluate your suggestion? Now that I think of it, maybe shouldn't think of the case the API is being used incorrectly.
shikhar
Than I don't understand "I was considering the case where the disconnection is not done properly". If you (the client API) control the disconnection, what's the problem?
ivan_ivanovich_ivanoff
The problem I was considering was the threads dying with an error, when the API user does not call disconnect() which stops the threads. But that doesn't really matter, if the object is up for garbage collection, clearly the API user would not be affected by an error in that thread -- so I guess this whole discussion was futile. Thanks for helping me clear my own head though.
shikhar