Stream confusion
Nathan Reynolds
numeralnathan at gmail.com
Wed Nov 22 20:19:09 UTC 2023
When the virtual thread hits the read(), it blocks. The virtual thread's
call stack is copied off the carrier thread's stack. When the virtual
thread unblocks, another carrier thread copies the virtual thread's call
stack back to the carrier thread's stack. Both of these operations require
synchronization (or happens before) to ensure the virtual thread's stack is
safely passed from one carrier thread to another carrier thread. This
synchronization ensures the passing of "this" from one carrier thread to
another carrier thread is safe. Hence, the unsafe() method is safe with
regards to a virtual thread executing on several different carrier threads.
unsafe() is not safe from multiple virtual threads calling it on the same
"this". unsafe() is not safe from multiple OS threads calling it on the
same "this".
On Wed, Nov 22, 2023 at 11:44 AM Mark Raynsford <org.openjdk at io7m.com>
wrote:
> On Wed, 2023-11-22 at 10:24 -0800, Nathan Reynolds wrote:
> >
> > I haven't played with Loom threads yet. From what I have read, it
> > doesn't
> > sound like Loom threads change the functional behavior of the
> > program.
> > Loom threads only change the performance behavior.
>
> They actually do. I was surprised by (and bitten by this):
>
> private final Map<String, String> data;
>
> void unsafe()
> {
> this.data.put("x", "y");
> System.in.read();
> this.data.put("x", "z");
> }
>
> The above unsafe() method is safe when called on a single platform
> thread. This is just normal "thread confinement" of the kind we've
> been using for years. The unsafe() method isn't safe when called by
> a single virtual thread. Why? Because the call to System.in.read()
> will cause the virtual thread to yield, and it may be resumed on
> a different _carrier_ thread after the read() call finishes. Nothing
> ensures those calls to Map.put() will result in safe publication.
>
> It just means that code that was safe to call on a single platform
> thread that assumed thread confinement (and so didn't synchronize its
> own private data) will break in perhaps surprising ways when called on
> a single virtual thread.
>
> --
> Mark Raynsford | https://www.io7m.com
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231122/0c10e2ca/attachment.htm>
More information about the amber-dev
mailing list