Is SharedSecrets thread-safe?

David Holmes david.holmes at oracle.com
Mon Dec 28 22:42:08 UTC 2020


Please take this to the core-libs-dev mailing list, the discuss list is 
not for these kinds of technical discussions.

Thanks,
David

On 29/12/2020 3:36 am, 
some-java-user-99206970363698485155 at vodafonemail.de wrote:
> Hello,
> the class `jdk.internal.access.SharedSecrets` provides getter methods which all look similar to this:
> ```
> if (static_field == null) {
>    initialize();
> }
> return static_field;
> ```
> 
> However, neither the static fields are `volatile` nor are the getter methods synchronized. So if my
> understanding of the Java Memory Model is correct, the compiler is free to reorder the two static
> field reads. So it is in theory possible that the first read yields a non-`null` value, but the
> second read yields a `null` value which leads to incorrect behavior (for further reading [1]).
> 
> It is probably rather unlikely that this actually happens because `SharedSecrets` is in most cases
> accessed from static initializers (which are only run once) and because not many classes access the
> same `SharedSecrets` fields.
> 
> Is this analysis correct or did I forget to consider parts of the Memory Model logic, or is there
> some JVM magic I am missing?
> 
> Kind regards
> 
> [1] https://shipilev.net/blog/2016/close-encounters-of-jmm-kind/#wishful-benign-is-resilient
> 


More information about the discuss mailing list