Fwd: questions about guava Suppliers

Skip to first unread message

Chris Povirk

Sep 24, 2021, 11:05:26 AMSep 24
to guava-discuss

---------- Forwarded message ---------
From: Yang Song <heifr...@gmail.com>
Date: Fri, Sep 24, 2021 at 11:04 AM
Subject: questions about guava Suppliers
To: <cpo...@google.com>

Pardon me for a question about guava Suppliers.

I noticed there are two class in Suppliers, MemoizingSupplier and
NonSerializableMemoizingSupplier. The codes are similar, but the
delegate field is not the same, one is volatile and the other is not.

I cannot understand why. I think both can be non-volatile, or there is
something that i missed. Could you help explain a bit?

Thank you!

Benjamin Manes

Sep 24, 2021, 1:10:01 PMSep 24
to Chris Povirk, guava-discuss
My guess is that this might have been to protect against wrong lazily initialized static fields. While final and volatile fields have happens-before semantics, plain fields do not. Assigning to a plain static field after initialization would not insert a memory barrier, so the below logic was unfortunately. common pre-Java 5. In that case not only could the supplier be set twice, but another thread might not see a fully-formed instance (null delegate). Even though that practice was squashed for server-side Java many years prior, it was sadly still common to see in Android at the time of this change (2016). Otherwise, it may have merely been a desire to make clear and simple code since volatiles are generally very cheap compared to the mental energy to debug concurrent code. =)

static Supplier<X> supplier;
if (supplier == null) {
  supplier = Suppliers.memoize(X::new)
return supplier;

Project site: https://github.com/google/guava
This group: http://groups.google.com/group/guava-discuss
This list is for general discussion.
To report an issue: https://github.com/google/guava/issues/new
To get help: http://stackoverflow.com/questions/ask?tags=guava
You received this message because you are subscribed to the Google Groups "guava-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to guava-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/guava-discuss/CAEvq2nq7J%3Dzm33i20xstq%3DzX3h76tGEqQaLKFgquix_5X7P7zQ%40mail.gmail.com.
Reply all
Reply to author
0 new messages