Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions docs/decisions/ADR-003-imports-in-intellij-idea.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
# ADR-003: In IntelliJ IDEA, Reformat leaves the imports, and Optimize imports is to become ours

## Status
Proposed
Accepted

## Date
2026-11-14
2026-11-14; revised 2026-11-24 for IntelliJ IDEA 2025.2 and later

## Context

With the plugin enabled, IntelliJ IDEA's Reformat runs open-java-format through the part-of-a-file entry ([ADR-001](ADR-001-one-output-per-entry-point.md)): `Main --character-ranges … --output-replacements`, which never touches imports. Imports are left to the IDE's Optimize imports, and that is the IDE's own `JavaImportOptimizer`, with the IDE's import layout and its thresholds for `import a.b.*;`. The command line, the GitHub Action and the build plugins then sort the imports again with `ImportOrderer`.

In the sources of IntelliJ IDEA 2024.2.6, the platform the plugin is built against:

- Every path that optimizes imports goes through `OptimizeImportsProcessor.collectOptimizers`: Optimize Imports; Reformat Code and Reformat Files with "Optimize imports"; Actions on Save; "Optimize imports" before a commit; the quick fix for an unused import; "Optimize imports on the fly". It asks `FormattingServiceUtil.findImportsOptimizingService(file)` for a service with `Feature.OPTIMIZE_IMPORTS`, and takes that service's `getImportOptimizers`.
- Every path that optimizes imports goes through `OptimizeImportsProcessor.collectOptimizers`: Optimize Imports; Reformat Code and Reformat Files with "Optimize imports"; Actions on Save; "Optimize imports" before a commit; the quick fix for missorted imports; "Optimize imports on the fly". The quick fix for an unused import, "Remove unused imports", deletes the imports it highlights itself (`RemoveAllUnusedImportsFix`). It asks `FormattingServiceUtil.findImportsOptimizingService(file)` for a service with `Feature.OPTIMIZE_IMPORTS`, and takes that service's `getImportOptimizers`.
- The plugin's `PalantirJavaFormatFormattingService.getFeatures()` returns `FORMAT_FRAGMENTS` only, and `getImportOptimizers` comes from `AbstractDocumentFormattingService`, which returns none; so `CoreFormattingService` answers with the IDE's optimizer.
- `processFile` of an optimizer runs in a background task under a read action (`OptimizeImportsProcessor.prepareTask`), so the time of one call counts.
- With "Optimize imports" on, Reformat Code on files and Reformat in the editor over the whole file run the formatter first and the optimizer after it (`AbstractLayoutCodeProcessor.getAllProcessors`, `FileInEditorProcessor`); over "only VCS-changed text" the editor runs the optimizer first.

From IntelliJ IDEA 2025.2 (build 252), two of those paths no longer reach `collectOptimizers`: "Optimize imports on the fly", and the quick fix for missorted imports. JetBrains made that fix a `ModCommandAction` (IDEA-370071, JetBrains/intellij-community@7ddc26cb5427), whose `perform` runs the IDE's own `JavaImportOptimizer` on a copy of the file; on the fly it runs in a non-blocking read action that expires once the file changes. This is read from the classes of IntelliJ IDEA 2026.3 (263.7307.200); those of 2025.1.7.2 still take the path above.

The plugin had an optimizer of its own for three weeks. google-java-format added one when it moved to the `FormattingService` API (google/google-java-format@84b2c9a2, 2023-03-02), running the formatter inside the IDE, for which users add `--add-exports` to the IDE's VM options. palantir/palantir-java-format#1078 followed it on 2024-04-26, and palantir/palantir-java-format#1089 removed the optimizer on 2024-05-21 as "slow". It called `FormatterService.fixImports`, which out of process runs `Main` without `--fix-imports-only`: a new JVM, and the whole file formatted, on every Optimize imports (#221). With the flag, one call on a small file takes about 20 ms with the native binary and 0.3 s with a new JVM.

## Decision

- **Reformat never changes imports**, over a part of a file or a whole one. It is the part-of-a-file entry.
- **Imports change only through Optimize imports.** Until the plugin's optimizer exists, that is the IDE's own.
- **The plugin's optimizer is to replace the IDE's** (#222): `getFeatures()` adds `OPTIMIZE_IMPORTS`, and `getImportOptimizers` returns an optimizer that calls `FormatterService.fixImports`. From then on it runs whenever Optimize imports is on, on every path listed above.
- **The plugin's optimizer is to replace the IDE's** (#222): `getFeatures()` adds `OPTIMIZE_IMPORTS`, and `getImportOptimizers` returns an optimizer that calls `FormatterService.fixImports`. From then on it runs whenever Optimize imports is on: on every path listed above in IntelliJ IDEA 2024.2 to 2025.1, and from 2025.2 on all of them but "Optimize imports on the fly" and the quick fix for missorted imports, which the IDE keeps to its own optimizer.
- **`fixImports` out of process passes `--fix-imports-only` first** (#221).

## Alternatives Considered
Expand All @@ -47,5 +49,6 @@ The plugin had an optimizer of its own for three weeks. google-java-format added

- Until #222, imports in IntelliJ IDEA follow the IDE's settings, and the command line or CI may sort them again.
- #222 depends on #221.
- The optimizer's time counts inside a read action: about 20 ms a call with the native binary, about 0.3 s with a new JVM, on a small file. "Optimize imports on the fly" runs while typing.
- The optimizer's time counts inside a read action: about 20 ms a call with the native binary, about 0.3 s with a new JVM, on a small file. "Optimize imports on the fly" runs while typing, in IntelliJ IDEA 2024.2 to 2025.1. The optimizer waits for the formatter in a way that a write action can interrupt, so typing does not wait for it (#253).
- From IntelliJ IDEA 2025.2, imports optimized on the fly or by the quick fix for missorted imports follow the IDE's rules, with the import layout that the plugin's `CodeStyleSettingsModifier` sets: they lose an unused `import a.b.*;`, which open-java-format keeps. An explicit Optimize Imports, Actions on Save and the command line give open-java-format's imports.
- The plugin's formatting service is asynchronous, and google-java-format's optimizer notes that it "can overwrite the results from the main formatter": the optimizer has to be checked in a running IDE.
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,29 @@
import com.intellij.formatting.service.FormattingNotificationService;
import com.intellij.lang.ImportOptimizer;
import com.intellij.lang.ImportOptimizer.CollectingInfoRunnable;
import com.intellij.openapi.application.ApplicationListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.util.ProgressIndicatorUtils;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.palantir.javaformat.intellij.PalantirJavaFormatFormattingService.PendingFormat;
import com.palantir.javaformat.java.FormatterException;
import com.palantir.javaformat.java.FormatterService;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntSupplier;
import java.util.function.LongConsumer;

/**
* Optimizes imports as the command line fixes them, with {@code FormatterService.fixImports}: the unused ones removed,
Expand All @@ -51,6 +63,14 @@ public String getUserNotificationInfo() {

private final PalantirJavaFormatFormattingService formattingService;

// The fixImports calls still running, by formatter and text. A read action that runs again after a write action,
// on the same text, waits for the call it started before instead of starting another: a JVM, in that mode.
private final Map<FixImportsCall, CompletableFuture<FixedImports>> running = new ConcurrentHashMap<>();

// The calls of processFile that wait for fixImports inside their read action, which a write action waits for.
private final AtomicInteger waiting = new AtomicInteger();
private final AtomicBoolean watchingWriteActions = new AtomicBoolean();

PalantirJavaFormatImportOptimizer(PalantirJavaFormatFormattingService formattingService) {
this.formattingService = formattingService;
}
Expand All @@ -61,12 +81,12 @@ public boolean supports(PsiFile file) {
}

// Called under a read action, in the background on most paths; the Runnable runs on the EDT under a write action.
// So the formatter runs here, and the Runnable only writes its text. EmptyRunnable tells the IDE that nothing
// changed. The formatter does not check for cancellation, so a write action waits for it: with "Optimize imports
// on the fly", typing waits (#253).
// So the formatter runs here, waited for in a way that a write action can interrupt, and the Runnable only writes
// its text. EmptyRunnable tells the IDE that nothing changed.
@Override
public Runnable processFile(PsiFile file) {
Project project = file.getProject();
debug(file, "asked on thread " + Thread.currentThread().getName());
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document == null) {
debug(file, "skipped, the file has no document");
Expand All @@ -91,14 +111,14 @@ public Runnable processFile(PsiFile file) {

String text = document.getText();
String fixedText;
var start = System.nanoTime();
try {
var start = System.nanoTime();
fixedText = formatter.get().fixImports(text);
fixedText = fixImports(file, formatter.get(), text);
if (logger.isDebugEnabled()) {
debug(
file,
String.format(
"fixImports ran in %s ms, length=%s, text changed: %s",
"waited %s ms for fixImports, length=%s, text changed: %s",
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start),
text.length(),
!fixedText.equals(text)));
Expand All @@ -109,6 +129,13 @@ public Runnable processFile(PsiFile file) {
reportError(project, Notifications.PARSING_ERROR_TITLE, Notifications.parsingErrorMessage(file.getName()));
return EmptyRunnable.getInstance();
} catch (ProcessCanceledException e) {
if (logger.isDebugEnabled()) {
debug(
file,
String.format(
"cancelled after waiting %s ms for fixImports, for a write action or by the user",
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
}
throw e;
} catch (RuntimeException e) {
// As in the formatting task: an error, so that it goes to the plugin's error reports.
Expand All @@ -135,6 +162,117 @@ public Runnable processFile(PsiFile file) {
};
}

/**
* The formatter's {@code fixImports}, on a pooled thread, so that a write action does not wait for it. The read
* action this runs in gives way to a write action only when it checks for cancellation, which the formatter never
* does: with "Optimize imports on the fly", every keystroke would wait for it (#253), in IntelliJ IDEA 2024.2 to
* 2025.1; from 2025.2 on the fly runs the IDE's own optimizer, not this one. Cancelled, this throws
* {@link ProcessCanceledException}, and a non-blocking read action, as on the fly, runs again after the write. The
* call already started runs to its end, for whoever asks for the same text meanwhile.
*/
private String fixImports(PsiFile file, FormatterService formatter, String text) throws FormatterException {
var call = new FixImportsCall(formatter, text);
var started = new AtomicBoolean();
var fixing = running.computeIfAbsent(call, key -> {
started.set(true);
return CompletableFuture.supplyAsync(
() -> {
try {
return key.run();
} finally {
// Kept only while it runs. Should it end first, the map holds this back until
// computeIfAbsent has put it in.
running.remove(key);
}
},
AppExecutorUtil.getAppExecutorService());
});
debug(file, started.get() ? "started fixImports" : "waits for the fixImports already running on the same text");
watchWriteActions();
waiting.incrementAndGet();
try {
return switch (ProgressIndicatorUtils.awaitWithCheckCanceled(fixing)) {
case FixedImports.Fixed fixed -> fixed.text();
case FixedImports.Failed failed -> throw failed.exception();
};
} finally {
waiting.decrementAndGet();
}
}

private record FixImportsCall(FormatterService formatter, String text) {
FixedImports run() {
try {
return new FixedImports.Fixed(formatter.fixImports(text));
} catch (FormatterException e) {
return new FixedImports.Failed(e);
}
}
}

/**
* What {@code fixImports} gives back from its thread: awaitWithCheckCanceled would wrap a {@link FormatterException}
* thrown there in a RuntimeException, which the optimizer takes for a fault of the plugin.
*/
private sealed interface FixedImports {
record Fixed(String text) implements FixedImports {}

record Failed(FormatterException exception) implements FixedImports {}
}

/** With debug logging on, logs how long each write action waits for the read lock while imports are optimized. */
private void watchWriteActions() {
if (logger.isDebugEnabled() && watchingWriteActions.compareAndSet(false, true)) {
var application = ApplicationManager.getApplication();
// For as long as the IDE runs: the plugin needs a restart to unload.
application.addApplicationListener(
new WriteActionWaits(waiting::get, wait -> {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Optimizing imports: a write action waited %s ms for the read lock",
TimeUnit.NANOSECONDS.toMillis(wait)));
}
}),
application);
}
}

/**
* Measures how long a write action waits for the read lock while an import optimization waits for fixImports:
* whether typing waits for the formatter (#253). Other read actions may hold the lock too, and their time counts
* as well.
*/
static final class WriteActionWaits implements ApplicationListener {
private final IntSupplier waiting;
private final LongConsumer report;

// From beforeWriteActionStart to writeActionStarted, on the thread of the write action: one at a time.
private boolean measuring;
private long requested;

/** waiting: how many optimizations wait for fixImports. report: given the wait in nanoseconds. */
WriteActionWaits(IntSupplier waiting, LongConsumer report) {
this.waiting = waiting;
this.report = report;
}

@Override
public void beforeWriteActionStart(Object action) {
// A write action inside another holds the lock already.
measuring = waiting.getAsInt() > 0
&& !ApplicationManager.getApplication().isWriteAccessAllowed();
requested = System.nanoTime();
}

@Override
public void writeActionStarted(Object action) {
if (measuring) {
measuring = false;
report.accept(System.nanoTime() - requested);
}
}
}

/**
* Whether a formatting request is pending on the document: one that is still formatting fixes the imports itself,
* and one whose text is not applied yet would lose it if the document changed now.
Expand Down
Loading
Loading