Is SharedSecrets thread-safe?
Hans Boehm
hboehm at google.com
Tue Dec 29 17:53:11 UTC 2020
On Tue, Dec 29, 2020 at 5:56 AM Johannes Kuhn <info at j-kuhn.de> wrote:
>
> Depends on what `initialize()` is.
>
> If it (at least) reads a volatile field, then the compiler can't reorder
> the second read before the first.
>
> - Johannes
I disagree with this claim. I have no idea whether concurrency is possible
here, so it may not matter. See below.
>
> On 29-Dec-20 14:42, 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;
> > ```
If static_field is not volatile, and set concurrently, then the first read
of static_field may return non-null and the second null, without
initialize() even being executed. The Java memory model does not prevent
reordering of non-volatile reads from the same field (for good reason).
Even if initialize() is executed and performs a volatile read, this
reasoning doesn't hold. The initial static_field read may be delayed past
the volatile read inside the conditional and hence, at least theoretically,
past the second read. Control dependencies don't order reads, either in
Java, or in modern weakly-ordered architectures with branch prediction.
This doesn't matter if initialize() sets static_field.
This all assumes that having two threads call initialize() is OK.
Java code with data races is extremely tricky and rarely correct.
Hans
More information about the core-libs-dev
mailing list