Core Java

JDK 10: FutureTask Gets a toString()

I’ve felt for a long time that, for most Java classes that have distinguishing attributes, developers should take the time to override Object.toString(), even if it’s just with an IDE-generated implementation or using a library class such as Apache Commons Lang‘s ToStringBuilder. The overloaded Objects.toString() methods also make this easier than ever if one wants to implement toString by hand. The JDK class FutureTask, introduced with J2SE 5, finally gets its own toString() implementation in JDK 10.

Richard Nichols‘s 2012 post “How to get the running tasks for a Java Executor…” highlights the omission of a toString() method on the FutureTask class. He wrote:


It seems odd that the API doesn’t include any way to gather info about what’s happening inside the
Executor, and also, there’s not even a
toString() implementation for wrapping classes like
FutureTask which would bubble your
Runnable or
Callable classes’
toString() methods.

Nichols’s post is in the context of his observation that “it’s quite difficult to actually expose at run-time what … Java’s Executor is actually doing at any point in time.”

Issue JDK-8186326 [“Make toString() methods of “task” objects more useful”] talks about aligning FutureTask toString() with that of CompletableFuture, which the issue states “already has a useful toString method, giving the current status.” An e-mail thread in late 2017 documents the discussions around the addition of toString() to FutureTask and other “task classes in j.u.c.” (java.util.concurrent).

The Javadoc comments for the new FutureTask.toString() method state, “The default implementation returns a string identifying this FutureTask, as well as its completion state. The state, in brackets, contains one of the strings ‘Completed Normally‘, ‘Completed Exceptionally‘, ‘Cancelled‘, or ‘Not completed‘.” Three of these four potential completion states for FutureTask‘s toString() are also potentially written as part of CompletableFuture‘s toString() [“Cancelled” is the exception].

The addition of a specific implementation of toString() to the FutureTask class in JDK 10 is a small one. However, for a developer “staring at output of toString for ‘task’ objects (Runnables, Callables, Futures) when diagnosing app failures” as described in JDK-8186326‘s “Problem” statement, this “small” addition is likely to be very welcome.

Published on Java Code Geeks with permission by Dustin Marx, partner at our JCG program. See the original article here: JDK 10: FutureTask Gets a toString()

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button