Question about threading implications of specification
Alan Bateman
Alan.Bateman at oracle.com
Wed Jul 13 02:05:40 PDT 2011
Gili wrote:
> Hi,
>
> The specification for AsynchronousByteChannel.read() talks about the
> operation taking place asynchronously, but what happens when the end of
> stream has been reached? Is an implementation allowed to fire the completion
> handler (or set the future) within the thread that invoked read()? From the
> implementation's point of view, there is no reason to carry out this
> operation asynchronously, because we already know the result. A similar case
> occurs if a user attempts to read into a buffer where remaining() returns 0
> (so we know the read operation must return 0).
>
> I ask because I've run into a race condition in my implementation. I'm
> invoking a completion handler that invokes notify() on itself when the
> operation completes. I then invoke the following user code:
>
> synchronize (handler)
> {
> foo.read(handler);
> handler.wait();
> }
>
> Note the user is assuming that the handler will be notified when the
> operation completes, but because read() runs synchronously at end of stream
> the handler gets notified before wait() and the latter will block forever.
>
> Does the specification require me to update Future/CompletionHandler in a
> separate thread or should users be aware of the fact that the thread that
> invokes read() may update said objects itself?
>
I read the stackoverflow thread and it sounds like you've got this
figured out. To summarize, this is something that channel types need to
specify. For the channel types defined in this API then the "Threading"
section of AsynchronousChannelGroup is where it explains that completion
handler can be invoked directly by the initiating thread.
AsynchronousFileChannel provider similar wording.
-Alan.
More information about the nio-discuss
mailing list