From bd030a8ca17fb1d309bcc2c34c09ef8dbd00a06e Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Tue, 24 Nov 2026 11:18:31 +0300 Subject: [PATCH 1/3] Return List.of() for the ops OpsBuilder.build finds at most ops OpsBuilder.build asks tokOps and reservations for the ops to insert at every op, and most ops have none. ArrayListMultimap.get makes a new empty list and a view of it for such a key, and the loop over it two iterators more. The two lines allocated 2.9 GB while formatting the 1,599 files of java.base in JDK 21, more than any other line of the formatter. Both are a ListMultimap now that returns List.of() for a key without values and leaves the rest to an ArrayListMultimap. build only reads what get returns, so that this list cannot be added to does not matter. Formatting those files allocates 20.9 GB instead of 23.1 GB, the output unchanged. Part of #229. --- .../com/palantir/javaformat/OpsBuilder.java | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java b/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java index eb6682dc5..81cffa09f 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java @@ -19,8 +19,9 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ForwardingListMultimap; import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; +import com.google.common.collect.ListMultimap; import com.palantir.javaformat.Indent.Const; import com.palantir.javaformat.Input.Tok; import com.palantir.javaformat.doc.Break; @@ -521,13 +522,32 @@ private static int getI(Input.Token token) { public record OpsOutput(List ops, InputMetadata inputMetadata) {} + /** + * An {@link ArrayListMultimap} whose {@link #get} of a key without values returns {@link List#of()}. {@link #build} + * asks for the ops to insert at every op and most have none, and {@link ArrayListMultimap#get} would make a new + * empty list and a view of it for each. The list returned for such a key cannot be added to. + */ + private static final class SparseListMultimap extends ForwardingListMultimap { + private final ArrayListMultimap delegate = ArrayListMultimap.create(); + + @Override + protected ListMultimap delegate() { + return delegate; + } + + @Override + public List get(K key) { + return delegate.containsKey(key) ? delegate.get(key) : List.of(); + } + } + /** Build a list of {@link Op}s from the {@code OpsBuilder}. */ public OpsOutput build() { markForPartialFormat(); // Rewrite the ops to insert comments. - Multimap tokOps = ArrayListMultimap.create(); + var tokOps = new SparseListMultimap(); // The room after a string literal for the NON-NLS markers written on its line, see Comment.makeNonNlsMarkers. - var reservations = ArrayListMultimap.create(); + var reservations = new SparseListMultimap(); var tokenOps = new HashMap(); Map tokenByIndex = null; int opsN = ops.size(); From 27931faa06fe849a0054c7fdde32242cb7fa15b3 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Tue, 24 Nov 2026 11:18:32 +0300 Subject: [PATCH 2/3] Memoize the width, flat text and range of a Doc in plain fields Each Doc held three Suppliers.memoize(...)::get, and each Level two more. For each that is a method reference, Guava's memoizing supplier, an object it locks on and the ::get of it: twelve objects for every Doc, which live as long as the Doc, and a Float for its width. They are plain fields now, computed when first asked for, as Level's hasCommentByFirstWord already was. The width is NaN until then, which computeWidth never returns, the depth of a Level -1, the others null. A Doc tree is built and laid out within one call of Formatter.format, in one thread, so the fields need no synchronization. ImmutableSupplier has no use left and goes. Formatting the 1,599 files of java.base in JDK 21 allocates 19.1 GB instead of 20.9 GB, the output unchanged. Part of #229. --- .../java/com/palantir/javaformat/doc/Doc.java | 27 +++++++++++---- .../javaformat/doc/ImmutableSupplier.java | 22 ------------ .../com/palantir/javaformat/doc/Level.java | 34 ++++++++++++------- 3 files changed, 42 insertions(+), 41 deletions(-) delete mode 100644 open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java index 57d6cbfd6..5d01a9d8a 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java @@ -16,7 +16,6 @@ package com.palantir.javaformat.doc; -import com.google.common.base.Suppliers; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.Range; import com.palantir.javaformat.CommentsHelper; @@ -24,6 +23,7 @@ import com.palantir.javaformat.Op; import com.palantir.javaformat.OpsBuilder; import com.palantir.javaformat.Output; +import org.jspecify.annotations.Nullable; /** * {@link com.palantir.javaformat.java.JavaInputAstVisitor JavaInputAstVisitor} outputs a sequence of {@link Op}s using @@ -37,14 +37,18 @@ public abstract class Doc extends HasUniqueId { static final Range EMPTY_RANGE = Range.closedOpen(-1, -1); static final DiscreteDomain INTEGERS = DiscreteDomain.integers(); + // The width, flat value and range, computed when first asked for, once the doc is complete. The width is NaN until + // then, which computeWidth never returns. @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedWidth = Suppliers.memoize(this::computeWidth)::get; + private float memoizedWidth = Float.NaN; @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedFlat = Suppliers.memoize(this::computeFlat)::get; + @Nullable + private String memoizedFlat; @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier> memoizedRange = Suppliers.memoize(this::computeRange)::get; + @Nullable + private Range memoizedRange; /** * Return the width of a {@code Doc}, or {@code Float.POSITIVE_INFINITY} if it must be broken. @@ -52,7 +56,10 @@ public abstract class Doc extends HasUniqueId { * @return the width */ final float getWidth() { - return memoizedWidth.get(); + if (Float.isNaN(memoizedWidth)) { + memoizedWidth = computeWidth(); + } + return memoizedWidth; } /** @@ -62,11 +69,17 @@ final float getWidth() { * @return the flat-string value */ public final String getFlat() { - return memoizedFlat.get(); + if (memoizedFlat == null) { + memoizedFlat = computeFlat(); + } + return memoizedFlat; } final Range range() { - return memoizedRange.get(); + if (memoizedRange == null) { + memoizedRange = computeRange(); + } + return memoizedRange; } /** diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java deleted file mode 100644 index 274e4eedc..000000000 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/ImmutableSupplier.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.palantir.javaformat.doc; - -import com.google.errorprone.annotations.Immutable; -import java.util.function.Supplier; - -@Immutable -interface ImmutableSupplier extends Supplier {} diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java index 98197c055..8790cd8df 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java @@ -20,7 +20,6 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import com.google.common.base.Suppliers; import com.google.common.collect.Range; import com.palantir.javaformat.BreakBehaviour; import com.palantir.javaformat.BreakBehaviour.BreakOnlyIfInnerLevelsThenFitOnOneLine; @@ -60,12 +59,12 @@ public final class Level extends Doc { private final List docs = new ArrayList<>(); // The elements of the level. - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedSplitsBreaks = - Suppliers.memoize(() -> splitByBreaks(docs))::get; + /** See {@link #splitsBreaks()}; computed when first asked for, once the docs are all in. */ + @Nullable + private SplitsBreaks memoizedSplitsBreaks; - @SuppressWarnings("Immutable") // Effectively immutable - private final ImmutableSupplier memoizedMaxDepth = Suppliers.memoize(() -> computeMaxDepth(docs))::get; + /** See {@link #getMaxDepth()}; -1 until it is computed, when first asked for, once the docs are all in. */ + private int memoizedMaxDepth = -1; /** See {@link #hasCommentByFirstWord()}; computed when first asked for, once the docs are all in. */ @Nullable @@ -144,7 +143,7 @@ public State computeBreaks(CommentsHelper commentsHelper, int maxWidth, State st "one line, comments laid out", state, explorationNode -> tryToLayOutLevelOnOneLine( - commentsHelper, maxWidth, state, memoizedSplitsBreaks.get(), explorationNode)) + commentsHelper, maxWidth, state, splitsBreaks(), explorationNode)) .markAccepted(); } else { newState = new BreakImpl(commentsHelper, maxWidth, state, childLevel).apply(getBreakBehaviour()); @@ -152,6 +151,14 @@ public State computeBreaks(CommentsHelper commentsHelper, int maxWidth, State st return childLevel.finishLevel(state.updateAfterLevel(newState)); } + /** The docs of this level split at its breaks. */ + private SplitsBreaks splitsBreaks() { + if (memoizedSplitsBreaks == null) { + memoizedSplitsBreaks = splitByBreaks(docs); + } + return memoizedSplitsBreaks; + } + /** Whether this level or a level in it holds a comment that the layout counts by its first word only. */ private boolean hasCommentByFirstWord() { if (hasCommentByFirstWord == null) { @@ -397,8 +404,8 @@ private Optional tryInlinePrefixOntoCurrentLine( if (keepIndent) { newState = newState.withIndentIncrementedBy(getPlusIndent()); } - return Optional.of(tryToLayOutLevelOnOneLine( - commentsHelper, maxWidth, newState, memoizedSplitsBreaks.get(), explorationNode)); + return Optional.of( + tryToLayOutLevelOnOneLine(commentsHelper, maxWidth, newState, splitsBreaks(), explorationNode)); } private Optional tryBreakLastLevel( @@ -679,7 +686,7 @@ private static SplitsBreaks splitByBreaks(List docs) { /** Compute breaks for a {@link Level} that spans multiple lines. */ private State computeBroken( CommentsHelper commentsHelper, int maxWidth, State state, Obs.ExplorationNode explorationNode) { - SplitsBreaks splitsBreaks = memoizedSplitsBreaks.get(); + SplitsBreaks splitsBreaks = splitsBreaks(); if (!splitsBreaks.breaks().isEmpty()) { state = state.withBrokenLevel(); @@ -752,7 +759,7 @@ public void write(State state, Output output) { } private void writeFilled(State state, Output output) { - SplitsBreaks splitsBreaks = memoizedSplitsBreaks.get(); + SplitsBreaks splitsBreaks = splitsBreaks(); // Handle first split. for (Doc doc : splitsBreaks.splits().get(0)) { doc.write(state, output); @@ -811,7 +818,10 @@ public String representation(State state) { * Get the approximation of the maximum depth of nested levels in this level tree (memoized). */ private int getMaxDepth() { - return memoizedMaxDepth.get(); + if (memoizedMaxDepth == -1) { + memoizedMaxDepth = computeMaxDepth(docs); + } + return memoizedMaxDepth; } /** From 9433355d3775b238282307d4e3bbae4b9833fd53 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Tue, 24 Nov 2026 11:40:10 +0300 Subject: [PATCH 3/3] Drop Error Prone's @Immutable from Break and NonBreakingSpace The width, flat text and range a Doc memoizes are plain fields now, and Error Prone proves a class @Immutable only when every field of its superclasses is final. Break and NonBreakingSpace, the two docs annotated so, needed @SuppressWarnings("Immutable") on those fields of Doc for it. Nothing else needed the annotation: without it, and without the suppressions, the module builds and checks as before. Both classes stay values that do not change once made: NonBreakingSpace has no fields, and Immutables generates the fields of Break final. Part of #229. --- .../src/main/java/com/palantir/javaformat/doc/Break.java | 2 -- .../src/main/java/com/palantir/javaformat/doc/Doc.java | 3 --- .../java/com/palantir/javaformat/doc/NonBreakingSpace.java | 2 -- 3 files changed, 7 deletions(-) diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java index c447e6f04..61331f893 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Break.java @@ -17,7 +17,6 @@ package com.palantir.javaformat.doc; import com.google.common.collect.Range; -import com.google.errorprone.annotations.Immutable; import com.palantir.javaformat.CommentsHelper; import com.palantir.javaformat.Indent; import com.palantir.javaformat.Op; @@ -27,7 +26,6 @@ import org.immutables.value.Value; /** A leaf node in a {@link Doc} for an optional break. */ -@Immutable @Value.Immutable public abstract class Break extends Doc implements Op { public abstract FillMode fillMode(); diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java index 5d01a9d8a..8d3a43056 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Doc.java @@ -39,14 +39,11 @@ public abstract class Doc extends HasUniqueId { // The width, flat value and range, computed when first asked for, once the doc is complete. The width is NaN until // then, which computeWidth never returns. - @SuppressWarnings("Immutable") // Effectively immutable private float memoizedWidth = Float.NaN; - @SuppressWarnings("Immutable") // Effectively immutable @Nullable private String memoizedFlat; - @SuppressWarnings("Immutable") // Effectively immutable @Nullable private Range memoizedRange; diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java index 31fcf769f..8b08fc903 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/NonBreakingSpace.java @@ -18,13 +18,11 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.Range; -import com.google.errorprone.annotations.Immutable; import com.palantir.javaformat.CommentsHelper; import com.palantir.javaformat.Op; import com.palantir.javaformat.Output; /** A Leaf node in a {@link Doc} for a non-breaking space. */ -@Immutable public final class NonBreakingSpace extends Doc implements Op { private NonBreakingSpace() {}