Skip to content

VisitorState.memoize and ClassName caches keep finished compilations alive #6405

Open

Description

@rsalvador

VisitorState.memoize and ClassName keep cached Types and Symbols through soft references, in suppliers and ClassNames that are usually static constants. Those values reach their compilation's Context, so in a JVM that runs many compilations, like a Bazel persistent worker or a Gradle compiler daemon, finished compilations stay reachable until the JVM clears soft references. With the default soft reference policy, an unused soft reference survives about one second per MB of free heap, so for hours in a worker with several GB free.

Paths from GC roots, from a heap dump of the reproduction below, with Error Prone built at 103086b, for example:

  • FormatStringUtils.LOCALE → ClassName → ClassName.cache → SoftReference → ClassName$CacheEntry → ClassSymbol → PathFileObject → JavacFileManager → Log → JavacMessages → Context
  • FutureReturnValueIgnored.FUTURE → VisitorState$Cache → VisitorState$Cache.cache → SoftReference → Type$ClassType → ClassSymbol → PathFileObject → JavacFileManager → Log → JavacMessages → Context

In that dump, 7 Contexts were reachable, the 6 counted compilations and one of the trivial ones: 5 through ClassName and 2 through VisitorState.memoize.

In a Bazel JavaBuilder worker, which by default runs 8 compilations at a time in one long-lived JVM, built at bazelbuild/bazel@14a179f6d2 and running Error Prone built at 103086b, 93 requests that compiled parts of Error Prone's own core sources left 18 finished compilations reachable after GC, with 0.35 GiB of heap in use. The number doesn't grow with the number of compilations (17 after 310 requests), because each cached value comes from the last compilation that used it. But each retained compilation keeps its symbol table and everything reachable from its Context, so the memory grows with the size of the compilations.

Reproduction

Repro.java (below) runs 6 javac compilations with Error Prone in one JVM, each using different checks, then a few trivial ones, runs GC, and counts the compilations whose Context is still reachable. Error Prone is loaded once, by the application class loader. With Error Prone built at 103086b on JDK 21:

6 of 6 completed compilations still reachable after GC, heap used 56 MB

The 2.53.0 release also left 6 of 6. Repro 10 300 work, with 10 compilations of 300 classes, left 5 of 10 reachable and 179 MB of heap in use after GC.

Repro.java and commands
import com.google.errorprone.ErrorProneJavacPlugin;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.BasicJavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

/**
 * Runs several javac + Error Prone compilations in one JVM, like a build tool's persistent worker,
 * and reports how many completed compilations (javac Contexts) are still reachable afterwards.
 *
 * <p>Error Prone is loaded once by the application class loader and registered on each task, so
 * no per-compilation class loader is involved. Usage: Repro PROJECTS CLASSES_PER_PROJECT WORK_DIR
 */
public class Repro {
  private static final String[] GROUPS = {
    // each group exercises different Error Prone checks, so each compilation fills different caches
    "java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(\"yyyy-MM-dd\"); return f.format(new java.util.Date()).length();",
    "return String.format(\"%s-%d\", \"a\", 1).length() + java.text.MessageFormat.format(\"{0}\", 1).length();",
    "java.util.List<String> l = new java.util.ArrayList<>(); java.util.Set<String> s = new java.util.HashSet<>(l); l.addAll(s); return l.contains(\"x\") || s.remove(\"y\") ? 1 : 0;",
    "java.time.Duration d = java.time.Duration.ofSeconds(5); return (int) d.plus(1, java.time.temporal.ChronoUnit.SECONDS).toMinutes() + java.time.LocalDate.of(2020, 1, 1).getDayOfMonth();",
    "Object lock = new Object(); synchronized (lock) { return Thread.currentThread().getName().hashCode(); }",
    "int[] a = {1}; int[] b = {1}; return java.util.Arrays.equals(a, b) ? java.util.Arrays.hashCode(a) : java.util.Objects.hash(1, 2);",
  };

  /** -Drepro.standardFileManager=true: a file manager with its own Context, as from ToolProvider. */
  private static final boolean SHARED_FM = Boolean.getBoolean("repro.standardFileManager");

  public static void main(String[] args) throws Exception {
    int projects = Integer.parseInt(args[0]);
    int classes = Integer.parseInt(args[1]);
    Path work = Path.of(args[2]);
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<WeakReference<Context>> contexts = new ArrayList<>();
    for (int p = 0; p < projects; p++) {
      contexts.add(compile(javac, project(work.resolve("p" + p), p, classes), work.resolve("out" + p)));
    }
    Path small = project(work.resolve("small"), -1, 1);
    for (int i = 0; i < 3; i++) {
      compile(javac, small, work.resolve("outsmall"));
    }
    for (int i = 0; i < 5; i++) {
      System.gc();
      Thread.sleep(200);
    }
    long reachable = contexts.stream().filter(r -> r.get() != null).count();
    long used = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
    System.out.printf(
        "%d of %d completed compilations still reachable after GC, heap used %d MB%n",
        reachable, projects, used >> 20);
  }

  /** Writes CLASSES classes that each call the API group of project P (P < 0: a trivial class). */
  static Path project(Path dir, int p, int classes) throws IOException {
    Files.createDirectories(dir);
    for (int c = 0; c < classes; c++) {
      String body = p < 0 ? "return 1;" : GROUPS[p % GROUPS.length];
      StringBuilder src = new StringBuilder("package p" + Math.max(p, 0) + ";\npublic class C" + c + " {\n");
      for (int m = 0; m < 20; m++) {
        src.append("  public int m").append(m).append("() { ").append(body).append(" }\n");
      }
      Files.writeString(dir.resolve("C" + c + ".java"), src.append("}\n"));
    }
    return dir;
  }

  static WeakReference<Context> compile(JavaCompiler javac, Path dir, Path out) throws IOException {
    Files.createDirectories(out);
    // like Bazel's JavaBuilder: the file manager belongs to the compilation's Context
    Context context = SHARED_FM ? null : new Context();
    StandardJavaFileManager fm =
        SHARED_FM
            ? javac.getStandardFileManager(null, null, StandardCharsets.UTF_8)
            : new JavacFileManager(context, true, StandardCharsets.UTF_8);
    List<Path> files;
    try (var s = Files.list(dir)) {
      files = s.filter(f -> f.toString().endsWith(".java")).toList();
    }
    Iterable<? extends JavaFileObject> units = fm.getJavaFileObjectsFromPaths(files);
    List<String> opts = List.of("-XDcompilePolicy=simple", "--should-stop=ifError=FLOW", "-XDaddTypeAnnotationsToSymbol=true", "-proc:none", "-nowarn", "-Xlint:none", "-d", out.toString());
    JavacTask task =
        SHARED_FM
            ? (JavacTask) javac.getTask(null, fm, null, opts, null, units)
            : JavacTool.create().getTask(null, fm, null, opts, null, units, context);
    new ErrorProneJavacPlugin().init(task);
    // javac drops the task's reference to its Context when the task completes, so take it now
    WeakReference<Context> result = new WeakReference<>(((BasicJavacTask) task).getContext());
    if (!task.call()) {
      throw new IllegalStateException("compilation failed: " + dir);
    }
    fm.close();
    return result;
  }
}

Get error_prone_core-with-dependencies.jar: download https://repo1.maven.org/maven2/com/google/errorprone/error_prone_core/2.53.0/error_prone_core-2.53.0-with-dependencies.jar, or build master with mvn -pl core -am package -DskipTests and copy core/target/error_prone_core-1.0-HEAD-SNAPSHOT-with-dependencies.jar. Save it under that name next to Repro.java.

javac --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -cp error_prone_core-with-dependencies.jar -d classes Repro.java
java --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED -XX:+UseG1GC -Xmx2g -cp classes:error_prone_core-with-dependencies.jar Repro 6 1 work

We have a fix that keeps these values in a map owned by the compilation's Context, and will send a PR. In our large build, it cut the time spent in Javac actions during a full build, summed over the actions, from about 43,000 s to 29,000 s, and the full build from about 5,000 s to 4,000 s.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions