Skip to content

Commit

Permalink
Make google-java-format friendlier to TSAN
Browse files Browse the repository at this point in the history
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: 563181626
  • Loading branch information
cushon authored and google-java-format Team committed Sep 6, 2023
1 parent 28b199c commit 9f2cd68
Showing 1 changed file with 8 additions and 21 deletions.
29 changes: 8 additions & 21 deletions core/src/main/java/com/google/googlejavaformat/Doc.java
Expand Up @@ -19,13 +19,15 @@
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;
import com.google.googlejavaformat.Output.BreakTag;
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
Expand Down Expand Up @@ -102,28 +104,21 @@ public String toString() {
private static final DiscreteDomain<Integer> INTEGERS = DiscreteDomain.integers();

// Memoized width; Float.POSITIVE_INFINITY if contains forced breaks.
private boolean widthComputed = false;
private float width = 0.0F;
private final Supplier<Float> 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<String> flat = Suppliers.memoize(this::computeFlat);

// Memoized Range.
private boolean rangeComputed = false;
private Range<Integer> range = EMPTY_RANGE;
private final Supplier<Range<Integer>> range = Suppliers.memoize(this::computeRange);

/**
* Return the width of a {@code Doc}, or {@code Float.POSITIVE_INFINITY} if it must be broken.
*
* @return the width
*/
final float getWidth() {
if (!widthComputed) {
width = computeWidth();
widthComputed = true;
}
return width;
return width.get();
}

/**
Expand All @@ -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();
}

/**
Expand All @@ -146,11 +137,7 @@ final String getFlat() {
* @return the {@code Doc}'s {@link Range}
*/
final Range<Integer> range() {
if (!rangeComputed) {
range = computeRange();
rangeComputed = true;
}
return range;
return range.get();
}

/**
Expand Down

0 comments on commit 9f2cd68

Please sign in to comment.