Joe Hendrix wrote:
> Sorry if this question is overly naive, I'm pretty much
> just an average Java programmer. If a thread is in an interrupted
> state and invokes wait(), is it guaranteed to throw an
> InterruptedException?
Yes this is true for wait() - though as you say the spec is not
crystal clear on this.
For sleep() it's mostly true - but there is a grey area with sleep(0)
For join() it need not be true because the thread being joined may
already have terminated, so no blocking occurs and so there's no need
to check interruption.
> 3). Theoretically it seems that interrupt handling could
> be done by a
> JVM by just setting the interrupted status of a thread, issuing a
> notify, then throwing an InterruptedException the next time
> wait() was invoked.
In part it already works like that: interrupt sets a bit that gets
tested by certain methods (wait(), sleep(), join() - at some point -
or Thread.interrupted/isInterrupted in general). But we also want
interrupt to break a thread out of the blackening part of wait/sleep
(join() is a wait() under the covers). The problem is how to do this
and keep track of what was done. Unless a VM keeps track of exactly
what a thread is doing, how and where it is blocked, then interruption
is a stab in the dark to some extent. Typically a signal (SIGUSR1?) is
sent to the thread to kick it out of blocking system calls (and the
thread masks that signal if it doesn't want to be kicked out). But as
I've mentioned pthreads/POSIX allows pthread_cond_wait to return zero
when interrupted by a system call so if pthread_cond_wait is used at a
low-level then having it return normally doesn't tell the VM why it
returned: notification or interruption. The VM can see that the
threads' interrupt flag is set, but that could have happened after the
return. The only way to deal with this is to track all of the related
state explicitly - using a variation of the "specific notification"
pattern so that you always know why a thread returned from a blocking
call. (Timeouts just further complicate things.)
In my opinion, and experience, thread interruption is the single most
complicating aspect of all of the threading and synchronization stuff
in the VM.
David Holmes
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:45 EDT