From ec00b5af699090b794a9d128ce799550bc40c6eb Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 6 Sep 2023 10:35:07 -0700 Subject: [PATCH] Make google-java-format friendlier to TSAN This code does deliberate racy initialization of some memoized values, and there is a static final instance of the `Space` subclass that ends up being shared across multiple threads. Tested: sponge/1777b644-2dd8-420b-ad06-b4f17c893d8f PiperOrigin-RevId: 563146412 --- .../java/com/google/googlejavaformat/Doc.java | 29 +++++-------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/Doc.java b/core/src/main/java/com/google/googlejavaformat/Doc.java index d638ddb40..e755bc67e 100644 --- a/core/src/main/java/com/google/googlejavaformat/Doc.java +++ b/core/src/main/java/com/google/googlejavaformat/Doc.java @@ -19,6 +19,7 @@ import static java.lang.Math.max; import com.google.common.base.MoreObjects; +import com.google.common.base.Suppliers; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.Iterators; import com.google.common.collect.Range; @@ -26,6 +27,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.function.Supplier; /** * {@link com.google.googlejavaformat.java.JavaInputAstVisitor JavaInputAstVisitor} outputs a @@ -102,16 +104,13 @@ public String toString() { private static final DiscreteDomain INTEGERS = DiscreteDomain.integers(); // Memoized width; Float.POSITIVE_INFINITY if contains forced breaks. - private boolean widthComputed = false; - private float width = 0.0F; + private final Supplier width = Suppliers.memoize(this::computeWidth); // Memoized flat; not defined (and never computed) if contains forced breaks. - private boolean flatComputed = false; - private String flat = ""; + private final Supplier flat = Suppliers.memoize(this::computeFlat); // Memoized Range. - private boolean rangeComputed = false; - private Range range = EMPTY_RANGE; + private final Supplier> range = Suppliers.memoize(this::computeRange); /** * Return the width of a {@code Doc}, or {@code Float.POSITIVE_INFINITY} if it must be broken. @@ -119,11 +118,7 @@ public String toString() { * @return the width */ final float getWidth() { - if (!widthComputed) { - width = computeWidth(); - widthComputed = true; - } - return width; + return width.get(); } /** @@ -133,11 +128,7 @@ final float getWidth() { * @return the flat-string value */ final String getFlat() { - if (!flatComputed) { - flat = computeFlat(); - flatComputed = true; - } - return flat; + return flat.get(); } /** @@ -146,11 +137,7 @@ final String getFlat() { * @return the {@code Doc}'s {@link Range} */ final Range range() { - if (!rangeComputed) { - range = computeRange(); - rangeComputed = true; - } - return range; + return range.get(); } /**