Ensuring atomicity of long values
forax at univ-mlv.fr
forax at univ-mlv.fr
Sat Oct 21 09:29:01 UTC 2023
> From: "-" <liangchenblue at gmail.com>
> To: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "valhalla-dev" <valhalla-dev at openjdk.org>
> Sent: Saturday, October 21, 2023 11:10:07 AM
> Subject: Re: Ensuring atomicity of long values
> Thank you for your quick response!
> On Sat, Oct 21, 2023 at 4:46 PM Remi Forax < [ mailto:forax at univ-mlv.fr |
> forax at univ-mlv.fr ] > wrote:
>> By default, a null restricted value class does not allow tearing by default so
>> wrapping a long should be enough (I hope).
> News of relief.
:)
> On a side note, if a non-atomic class allows tearing, then Long and Double
> wrappers cannot be migrated to be non-atomic (as you imply in your recent "Not
> yet again!" against LooselyConsistentValue interface):
> Compare a non-final long field and a non-final Long field. The long field can be
> read with tearing, but Long, an object reference, cannot. Say we write 1L<<32
> and 1 to the field from 2 threads racily, then long read can yield 0, 1,
> 1L<<32, 1L<<32 | 1, but Long read can only yield null, 1, 1L<<32 (as the final
> long field is published and visible when the Long object is visible)
Long will never tear, but Long! (note, there is a bang here) will tear. Long! and long have exactly the same semantics with respect to tearing.
>From the spec POV, if you want flattenes on heap you need both a value class with an implicit constructor AND using ! at use site (where the field is declared).
After, a specific VM can do heroics and discover that the actual CPU supports atomic 128 bits read/write using vector instructions and decide to store a Long (no bang) as a 128 bits values, 64 for the value and 1 for null or not. But this is a tradeoff, using more memory may backfire.
>> class LongWrapper {
>> long value;
>> implicit LongWrapper();
>> LongWrapper(long value) { this.value = value; }
>> }
>> class Foo {
>> LongWrapper! w; // this is a non-tearing long
>> }
>> From the spec POV, there is no garantee that an instance will not be a pointer
>> instead of the direct value but given that Java only works on platforms (even
>> 32 bits) that are able to write 64 bits atomically (otherwise you can not
>> implement the VarHandle API), practically, it should be ok.
> Agreed. Even if VarHandle and 64-bit atomic read/writes aren't used, JVM can
> always fall back to traditional final field handling and heap object layouts,
> which is still functionally correct.
Yes.
In Java, a developer does not control where his code run. So the semantics has to be the same for a wide range of hardware.
regards,
Rémi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/valhalla-dev/attachments/20231021/dd438d99/attachment.htm>
More information about the valhalla-dev
mailing list