RFR: 8355301: Simplify Throwable::printStackTrace by using record [v4]

Chen Liang liach at openjdk.org
Fri Apr 25 14:24:50 UTC 2025


On Fri, 25 Apr 2025 07:54:03 GMT, Johannes Döbler <duke at openjdk.org> wrote:

>>> @AlanBateman I have modified it to use interface + record. Is this what you want?
>> 
>> I don't object to changing it to interface + record but it feels more like needless code churn. I really disliked the next version that used printStackTrace0(Object printer) as it immediately invites another re-write.
>
> The record has fewer source lines but doesn't the generated record class have a getter, toString(), hashCode() and equals(Object) which are not needed here?
> What about using a lock parameter and a method handle to pass in the required features of PrintStream and PrintWriter:
> 
> public void printStackTrace(PrintWriter pw) {
>     printStackTrace(pw, pw::println);
> }
> 
> public void printStackTrace(PrintStream ps) {
>     printStackTrace(ps, ps::println);
> }
> 
> private void printStackTrace(Object lock, Consumer<Object> println) {
>     synchronized(lock) {
>     	...
>         println.accept(this);
>     	...
>     }
> }

FYI lambda expressions depend on java.lang.invoke, and if anything initialized before that throws an exception and needs to print stack trace, the VM will fail with a traceless `StackOverflowError` I think. Consumer class is fine for early loading, but  to implement that, we fall back to records again.

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

PR Review Comment: https://git.openjdk.org/jdk/pull/24795#discussion_r2060345723


More information about the core-libs-dev mailing list