views:

126

answers:

2

My scenario is as follows:

I am implementing a server that must timeout or produce a response within the specified timeout period for each request. Thus each request is ensured a response from the server's point of view (the response, of course, might not reach the client due to transport layer failure, etc...).

In order to implement the above semantics, each request spawns a thread (actually retrieves an available one from a thread pool) and awaits its response via a notify on a sync object. The wait period is limited with a timeout param sent to Object's wait method. The spawned thread delegates the request to an object that actually knows how to handle the request. This object's call API is known, but there is no known service level agreement which would specify that a call will never hang indefinitely. (Specifically in my case, the Server is actually a CORBA client - but that is not the point.)

Now, what interests me, is whether or not there is a way for me to somehow detect that that thread is not responsive and then kill it (interrupt it) even though I am currently blocked on a method call?

By the way, I know that I can keep a reference to the thread object and after a pre-specified amount of time call its interrupt() method. That unfortunately does not ensure "interrupt" semantics...

Java Thread Primitive Deprecation

Thanks all

+1  A: 

Try using an ExecutorService and make the actual business logic be performed in a Callable. The Future returned by the ExecutorService has a get() that allows you to specify how long you will wait...

Fried Hoeben
I don't think that calling the get() method and timing out will then cause the ExecutorService to regard the thread issued to the running of the Callable as reclaimable. Or does it?
Yaneeve
@Yaneeve, you are correct that this doesn't get around the issues you are trying to avoid.
PSpeed
It doesn't reclaim the thread, but your server is able to give an answer to its client within the specified time, which I gathered was your foremost concern. And it is especially nice that this works irrespective of the number of external calls, disk IO, or calculations being done in the service's business logic (i.e. you get separation of concerns).Dealing with the 'runaway thread' then becomes an implementation issue, where interrupt() could play its part (being blocked on a CORBA call is probably being blocked on network IO where interrupting normally does work).
Fried Hoeben
+3  A: 

I think if you can't rely on interrupt() semantics then you may be out of luck. There is no reliable or safe way to forcefully terminate a thread. It's dangerous in any language.

I would hope that interrupt() would get you what you need even if it could be circumvented. The CORBA calls should be going through the standard network classes and therefore should properly interrupt on any blocking calls.

It's the best you can do short of spawning full child processes.

PSpeed