Stream confusion
Mark Raynsford
org.openjdk at io7m.com
Wed Nov 22 19:44:21 UTC 2023
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
More information about the amber-dev
mailing list