RFR: 8333086: Using Console.println is unnecessarily slow due to JLine initalization

Jan Lahoda jlahoda at openjdk.org
Thu May 30 13:55:14 UTC 2024


Consider these two programs:


public class SystemPrint {
    public static void main(String... args) {
        System.err.println("Hello!");
    }
}

and:

public class IOPrint {
    public static void main(String... args) {
        java.io.IO.println("Hello!");
    }
}


They do the same conceptual thing - write a text to the output. But, `IO.println` delegates to `Console.println`, which then delegates to a `Console` backend, and the default backend is currently based on JLine.

The issues is that JLine takes a quite a long time to initialize, and in a program like this, JLine is not really needed - it is used to provide better editing experience when reading input, but there's no reading in these programs.

For example, on my computer:

$ time java -classpath /tmp SystemPrint 
Hello!

real    0m0,035s
user    0m0,019s
sys     0m0,019s

$ time java -classpath /tmp --enable-preview IOPrint 
Hello!

real    0m0,165s
user    0m0,324s
sys     0m0,042s


The proposal herein is to delegate to the simpler `Console` backend from `java.base` as long as the user only uses methods that print to output, and switch to the JLine delegate when other methods (typically input) is used. Note that while technically `writer()` is a method doing output, it will force JLine initialization to avoid possible problems if the client caches the writer and uses it after switching the delegates.

With this patch, I can get timing like this:

$ time java --enable-preview -classpath /tmp/ IOPrint 
Hello!

real    0m0,051s
user    0m0,038s
sys     0m0,020s


which seems much more acceptable.

There is also #19467, which may reduce the time further.

A future work might focus on making JLine initialize faster, but avoiding JLine initialization in case where we don't need it seems like a good step to me in any case.

-------------

Commit messages:
 - Cleanup, addint test.
 - Using println correctly, flushing the java.base delegate before switching to JLine.
 - Force Terminal when writer is requested.
 - Attempting to speedup start by delaying initialization of JLine until really necessary.

Changes: https://git.openjdk.org/jdk/pull/19479/files
  Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=19479&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8333086
  Stats: 225 lines in 2 files changed: 212 ins; 1 del; 12 mod
  Patch: https://git.openjdk.org/jdk/pull/19479.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/19479/head:pull/19479

PR: https://git.openjdk.org/jdk/pull/19479


More information about the core-libs-dev mailing list