RFR: 8261445: Use memory_order_relaxed for os::random().

Aleksey Shipilev shade at openjdk.java.net
Wed Feb 10 07:36:38 UTC 2021


On Tue, 9 Feb 2021 22:25:14 GMT, David Holmes <dholmes at openjdk.org> wrote:

>> os::random() is used a lot (once for every class) during HotSpot initialization, and it defaults to using a compare-and-swap operation with memory_order_conservative. We don't need that: it should be memory_order_relaxed.
>
> This seems fine to me too.
> 
> Thanks,
> David

> > It seems superficially fine, given unsynchronized read of `_rand_seed` prior to that. But I have to wonder if in absence of any memory ordering semantics, this loop is guaranteed to terminate? That is, can't a sufficiently hostile optimizer reduce it to the CAS loop that always expects a constant "oldval" seed?
> 
> I can't see any problem here. `_rand_seed` is volatile so the compiler must preserve all accesses to it. And all processors I'm aware of are single-copy atomic which means that all accesses to the same memory location are ordered.

Yes, that looks fine. If we match the C++11 semantics of `relaxed`, we still maintain the single modification order of the variable. I would suggest we load `_rand_seed` with `Atomic::load(&_rand_seed)` as a good style, though.

-------------

PR: https://git.openjdk.java.net/jdk/pull/2484


More information about the hotspot-runtime-dev mailing list