From f622dd95f5b6e0b9c18e1726ed2a921d840cfc77 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 23:56:22 +0300 Subject: [PATCH 1/4] Let a write action interrupt the import optimizer while the formatter runs With "Optimize imports on the fly" ticked, IntelliJ IDEA 2024.2 to 2025.1 run the plugin's import optimizer in a non-blocking read action after a highlighting pass, and the optimizer called fixImports right there. A non-blocking read action gives way to a write action only when it checks for cancellation, which the formatter never does, so the write action of the next keystroke waited for the formatter: about 0.3 s with a JVM of its own, 20 ms with the native binary (#253). From 2025.2 the IDE optimizes on the fly with its own JavaImportOptimizer and never asks the plugin. fixImports now runs on a pooled thread, and the optimizer waits for it with ProgressIndicatorUtils.awaitWithCheckCanceled. A pending write action cancels the read action, and the platform runs it again after the write. The call already started runs to its end, and one that is still running is shared, by formatter and text, with the calls that ask for the same text meanwhile: a read action run again after a write elsewhere waits for it instead of starting another JVM. A call is kept only while it runs. What the formatter throws comes back from its thread as a value: awaitWithCheckCanceled would wrap a FormatterException in a RuntimeException, and the optimizer would report a file it cannot parse as a fault of the plugin. Fixes #253 --- .../PalantirJavaFormatImportOptimizer.java | 76 +++++++++- ...PalantirJavaFormatImportOptimizerTest.java | 139 ++++++++++++++++++ 2 files changed, 209 insertions(+), 6 deletions(-) diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java index 0d328b0e7..ae725169b 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java @@ -20,13 +20,19 @@ 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; /** @@ -51,6 +57,10 @@ 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> running = new ConcurrentHashMap<>(); + PalantirJavaFormatImportOptimizer(PalantirJavaFormatFormattingService formattingService) { this.formattingService = formattingService; } @@ -61,9 +71,8 @@ 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(); @@ -91,14 +100,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(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))); @@ -109,6 +118,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. @@ -135,6 +151,54 @@ 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(FormatterService formatter, String text) throws FormatterException { + var fixing = running.computeIfAbsent( + new FixImportsCall(formatter, text), + key -> 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())); + return switch (ProgressIndicatorUtils.awaitWithCheckCanceled(fixing)) { + case FixedImports.Fixed fixed -> fixed.text(); + case FixedImports.Failed failed -> throw failed.exception(); + }; + } + + 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 {} + } + /** * 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. diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java index e69d569fd..050a04732 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java @@ -15,8 +15,11 @@ package com.palantir.javaformat.intellij; import static java.util.Objects.requireNonNull; +import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Range; import com.intellij.application.options.CodeStyle; import com.intellij.codeInsight.actions.OptimizeImportsProcessor; import com.intellij.codeInsight.actions.ReformatCodeProcessor; @@ -26,7 +29,14 @@ import com.intellij.formatting.service.FormattingService; import com.intellij.ide.impl.TrustedProjects; import com.intellij.lang.ImportOptimizer; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ReadAction; +import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.progress.util.AbstractProgressIndicatorBase; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; @@ -38,9 +48,16 @@ import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; import com.intellij.testFramework.fixtures.TestFixtureBuilder; import com.palantir.javaformat.intellij.PalantirJavaFormatSettings.StoredSettings; +import com.palantir.javaformat.java.FormatterException; +import com.palantir.javaformat.java.FormatterService; +import com.palantir.javaformat.java.Replacement; import java.io.File; +import java.util.Collection; import java.util.List; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -186,6 +203,76 @@ void optimize_imports_in_an_untrusted_project_changes_nothing_and_says_why_in_th } } + @Test + void a_write_action_does_not_wait_for_the_formatter_to_fix_the_imports() throws Exception { + PsiFile file = createPsiFile(UNOPTIMIZED); + var formatter = new BlockingFormatterService(); + delegatingFormatter.formatter = formatter; + var optimizer = delegatingFormatter.getImportOptimizers(file).iterator().next(); + try { + // As the platform runs it on the fly: in a read action that gives way to a write action, then runs again. + var optimizing = ApplicationManager.getApplication() + .executeOnPooledThread(() -> ReadAction.nonBlocking(() -> optimizer.processFile(file)) + .executeSynchronously()); + assertThat(formatter.started.await(10, SECONDS)).isTrue(); + + // The write action of a keystroke, which is not to wait for the formatter to return. + ApplicationManager.getApplication() + .executeOnPooledThread(() -> WriteAction.runAndWait(() -> {})) + .get(10, SECONDS); + + formatter.release.countDown(); + assertThat(optimizing.get(10, SECONDS)).isNotSameAs(EmptyRunnable.getInstance()); + } finally { + formatter.release.countDown(); + } + } + + @Test + void optimizing_the_same_text_again_waits_for_the_fix_already_running() throws Exception { + PsiFile file = createPsiFile(UNOPTIMIZED); + var formatter = new BlockingFormatterService(); + delegatingFormatter.formatter = formatter; + var optimizer = delegatingFormatter.getImportOptimizers(file).iterator().next(); + try { + var first = ApplicationManager.getApplication() + .executeOnPooledThread(() -> ReadAction.compute(() -> optimizer.processFile(file))); + assertThat(formatter.started.await(10, SECONDS)).isTrue(); + + // Releases the formatter once the second call waits for it, by when it has found the first one running. + var releasing = new AbstractProgressIndicatorBase() { + @Override + public void checkCanceled() { + if (StackWalker.getInstance() + .walk(frames -> frames.anyMatch( + frame -> frame.getMethodName().equals("awaitWithCheckCanceled")))) { + formatter.release.countDown(); + } + super.checkCanceled(); + } + }; + var second = ApplicationManager.getApplication() + .executeOnPooledThread(() -> ProgressManager.getInstance() + .runProcess(() -> ReadAction.compute(() -> optimizer.processFile(file)), releasing)); + + assertThat(second.get(10, SECONDS)).isNotSameAs(EmptyRunnable.getInstance()); + assertThat(first.get(10, SECONDS)).isNotSameAs(EmptyRunnable.getInstance()); + assertThat(formatter.calls.get()).isEqualTo(1); + } finally { + formatter.release.countDown(); + } + } + + @Test + void optimize_imports_leaves_the_file_alone_when_the_formatter_fails_on_it() { + PsiFile file = createPsiFile(UNOPTIMIZED); + delegatingFormatter.formatter = new FailingFormatterService(); + + run(new OptimizeImportsProcessor(file.getProject(), file)); + + assertThat(file.getText()).isEqualTo(UNOPTIMIZED); + } + private String commandLineOutput(String input) throws Exception { return delegatingFormatter .getFormatter(fixture.getProject()) @@ -272,9 +359,56 @@ public void onError(String title, String message, int offset) { } } + /** Fixes the imports only once released, to stand for a formatter that takes its time. */ + private static final class BlockingFormatterService extends UnsupportedFormatterService { + private final CountDownLatch started = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final AtomicInteger calls = new AtomicInteger(); + + @Override + public String fixImports(String input) { + calls.incrementAndGet(); + started.countDown(); + try { + if (!release.await(30, SECONDS)) { + throw new IllegalStateException("Never released"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + return "fixed"; + } + } + + /** Fails as a formatter of its own process does on a file it cannot parse. */ + private static final class FailingFormatterService extends UnsupportedFormatterService { + @Override + public String fixImports(String input) throws FormatterException { + throw new FormatterException("cannot parse"); + } + } + + private abstract static class UnsupportedFormatterService implements FormatterService { + @Override + @SuppressForbidden(reason = "FormatterService, kept in the SPI for compatibility, returns ImmutableList") + public ImmutableList getFormatReplacements(String input, Collection> ranges) { + throw new UnsupportedOperationException(); + } + + @Override + public String formatSourceReflowStringsAndFixImports(String input) { + throw new UnsupportedOperationException(); + } + } + private static final class DelegatingFormatter extends PalantirJavaFormatFormattingService { private boolean optimizerInvoked = false; + // The formatter the optimizer runs instead of the project's. + @Nullable + private FormatterService formatter; + DelegatingFormatter() { this.setPluginDescriptor( requireNonNull(FormattingService.EP_NAME.findExtension(PalantirJavaFormatFormattingService.class)) @@ -299,6 +433,11 @@ public Runnable processFile(PsiFile file) { }); } + @Override + Optional getFormatter(Project project) { + return formatter != null ? Optional.of(formatter) : super.getFormatter(project); + } + @Override protected FormattingTask createFormattingTask(AsyncFormattingRequest request) { return requireNonNull(super.createFormattingTask(request)); From 3513749143fe14228b4c6a80622fcfba7808f046 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 23:57:20 +0300 Subject: [PATCH 2/4] Log how long a write action waits while the import optimizer runs With debug logging on, the log could tell how long fixImports took but not whether typing waited for it, which is what #253 is about. The optimizer now logs the thread it was asked on, and whether it started fixImports or waits for the call already running on the same text. Once debug logging is on, it also listens to write actions: while an optimization waits for fixImports, it logs how long each write action waited for the read lock, from beforeWriteActionStart to writeActionStarted. Other read actions may hold the lock too, and their time counts as well. The listener stays until the IDE restarts, which the plugin needs to unload. --- .../PalantirJavaFormatImportOptimizer.java | 112 +++++++++++++++--- ...PalantirJavaFormatImportOptimizerTest.java | 26 ++++ 2 files changed, 119 insertions(+), 19 deletions(-) diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java index ae725169b..259a8b43d 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java @@ -17,6 +17,8 @@ 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; @@ -34,6 +36,10 @@ 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, @@ -61,6 +67,10 @@ public String getUserNotificationInfo() { // on the same text, waits for the call it started before instead of starting another: a JVM, in that mode. private final Map> 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; } @@ -76,6 +86,7 @@ public boolean supports(PsiFile file) { @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"); @@ -102,7 +113,7 @@ public Runnable processFile(PsiFile file) { String fixedText; var start = System.nanoTime(); try { - fixedText = fixImports(formatter.get(), text); + fixedText = fixImports(file, formatter.get(), text); if (logger.isDebugEnabled()) { debug( file, @@ -159,24 +170,34 @@ public Runnable processFile(PsiFile file) { * {@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(FormatterService formatter, String text) throws FormatterException { - var fixing = running.computeIfAbsent( - new FixImportsCall(formatter, text), - key -> 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())); - return switch (ProgressIndicatorUtils.awaitWithCheckCanceled(fixing)) { - case FixedImports.Fixed fixed -> fixed.text(); - case FixedImports.Failed failed -> throw failed.exception(); - }; + 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) { @@ -199,6 +220,59 @@ 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. diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java index 050a04732..0cb88d08d 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java @@ -15,6 +15,7 @@ package com.palantir.javaformat.intellij; import static java.util.Objects.requireNonNull; +import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; @@ -47,6 +48,8 @@ import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; import com.intellij.testFramework.fixtures.TestFixtureBuilder; +import com.intellij.util.TimeoutUtil; +import com.palantir.javaformat.intellij.PalantirJavaFormatImportOptimizer.WriteActionWaits; import com.palantir.javaformat.intellij.PalantirJavaFormatSettings.StoredSettings; import com.palantir.javaformat.java.FormatterException; import com.palantir.javaformat.java.FormatterService; @@ -56,6 +59,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.jspecify.annotations.Nullable; @@ -263,6 +267,28 @@ public void checkCanceled() { } } + @Test + void measures_how_long_a_write_action_waits_for_the_read_lock() throws Exception { + var waits = new CopyOnWriteArrayList(); + // As though an optimization waited for the formatter all along. + ApplicationManager.getApplication() + .addApplicationListener(new WriteActionWaits(() -> 1, waits::add), fixture.getTestRootDisposable()); + var reading = new CountDownLatch(1); + var reader = ApplicationManager.getApplication() + .executeOnPooledThread(() -> ReadAction.run(() -> { + reading.countDown(); + TimeoutUtil.sleep(300); + })); + assertThat(reading.await(10, SECONDS)).isTrue(); + + ApplicationManager.getApplication() + .executeOnPooledThread(() -> WriteAction.runAndWait(() -> {})) + .get(10, SECONDS); + reader.get(10, SECONDS); + + assertThat(waits).anySatisfy(wait -> assertThat(wait).isGreaterThan(MILLISECONDS.toNanos(200))); + } + @Test void optimize_imports_leaves_the_file_alone_when_the_formatter_fails_on_it() { PsiFile file = createPsiFile(UNOPTIMIZED); From 3c43ad4214da916493a718444f8032bdddb1cd82 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Tue, 24 Nov 2026 00:02:09 +0300 Subject: [PATCH 3/4] Say in ADR-003 which IntelliJ IDEA versions optimize imports through the plugin ADR-003 listed, from the sources of IntelliJ IDEA 2024.2.6, every way of optimizing imports as going through OptimizeImportsProcessor.collectOptimizers, and so through the plugin's optimizer. From 2025.2 two of them do not: "Optimize imports on the fly", and the quick fix for missorted imports. JetBrains made that fix a ModCommandAction (IDEA-370071), whose perform runs the IDE's own JavaImportOptimizer; the classes of 2026.3 do, those of 2025.1.7.2 still take the old path. The decision now says on which paths the plugin's optimizer runs in which versions, and the consequences what imports optimized on the fly look like from 2025.2. The list also named the quick fix for an unused import, which even in 2024.2.6 is "Remove unused imports": RemoveAllUnusedImportsFix deletes the imports it highlights itself, and never asks an optimizer. The quick fix that went through collectOptimizers was the one for missorted imports. The consequence about the optimizer's time inside a read action says that typing no longer waits for it (#253). --- docs/decisions/ADR-003-imports-in-intellij-idea.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/decisions/ADR-003-imports-in-intellij-idea.md b/docs/decisions/ADR-003-imports-in-intellij-idea.md index dcd64312e..20814806e 100644 --- a/docs/decisions/ADR-003-imports-in-intellij-idea.md +++ b/docs/decisions/ADR-003-imports-in-intellij-idea.md @@ -4,7 +4,7 @@ Proposed ## Date -2026-11-14 +2026-11-14; revised 2026-11-24 for IntelliJ IDEA 2025.2 and later ## Context @@ -12,18 +12,20 @@ With the plugin enabled, IntelliJ IDEA's Reformat runs open-java-format through 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 @@ -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. From 419e46229736bb11eb24b28209e2692872484721 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Tue, 24 Nov 2026 00:12:27 +0300 Subject: [PATCH 4/4] Accept ADR-003 Both of its decisions are in: fixImports passes --fix-imports-only out of process (#221, in #236), and the plugin's optimizer replaces the IDE's (#222, in #255). --- docs/decisions/ADR-003-imports-in-intellij-idea.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/ADR-003-imports-in-intellij-idea.md b/docs/decisions/ADR-003-imports-in-intellij-idea.md index 20814806e..563c5a07e 100644 --- a/docs/decisions/ADR-003-imports-in-intellij-idea.md +++ b/docs/decisions/ADR-003-imports-in-intellij-idea.md @@ -1,7 +1,7 @@ # ADR-003: In IntelliJ IDEA, Reformat leaves the imports, and Optimize imports is to become ours ## Status -Proposed +Accepted ## Date 2026-11-14; revised 2026-11-24 for IntelliJ IDEA 2025.2 and later