Ensuring atomicity of long values

- liangchenblue at gmail.com
Sat Oct 21 09:10:07 UTC 2023


Thank you for your quick response!

On Sat, Oct 21, 2023 at 4:46 PM Remi Forax <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)

>
>   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.

> regards,
> Rémi
>
> Grateful,
Chen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/valhalla-dev/attachments/20231021/bb5f862c/attachment.htm>


More information about the valhalla-dev mailing list