I hope that most Java developers are aware of the Swing threading policy. It makes sense, except for that it’s so insanely hard to follow. And if you do follow it, I dare say there is no place with more ridiculous boilerplate.
Here’s two examples that recently got me scratching my head, gnashing my teeth, and eventually weep in disdain.
Case One: Display Download Progress
class Downloader { download() { progress.startDownload(); while(hasMoreChunks()) { downloadChunk(); progress.downloadedBytes(n); } progress.finishDownload(); } } class ProgressDisplay extends JPanel { JLabel label; startDownload() { SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText("Download started"); } }); } downloadedBytes(int n) { SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText("Downloaded bytes: " + n); } }); } finishDownload() { SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText("Download finished"); } }); } }
Solution? Easy! Just write your own JLabel
wrapper to hide this mess. Then a lengthy JTable
utility. Then a JProgressBar
wrapper. Then…
Case Two: Persist Component State
Task: Save JTable
state to disk. You’ve got to read table state in EDT, but writing to disk from EDT is not the the best idea.
Solution:
ExecutorService executor = Executors.newSingleThreadExecutor(); void saveState(final Table table) { SwingUtilities.invokeLater(new Runnable() { public void run() { TableColumns state = dumpState(table); executor.execute(new Runnable() { public void run() { saveToDisk(table.getTableKey(), state); } }); } }); }
Two inner classes, inheritance, all those publics
and voids
and parentheses. And there is no way to avoid that!
In a sane language, it could look like:
(defn save-state [table] (do-swing (let [state (dump-state table)] (future (save-to-disk table state)))))
All semantics. Little ceremony, almost no syntax. If you counted characters in both solutions, I guess the entire second snippet is as long as the first one somewhere to the invocation of invokeLater
. Before you get to the actual logic. No strings attached, do-swing
and future
are provided by the language or “official” utils.
Bottom Line
I recently saw two presentations by Venkat Subramaniam on polyglot programming where he mercilessly made fun of Java. In his (vaguely remembered) words, when you write such code for the whole day, you come back home and weep. You can’t sleep because you’re tormented by the thought of the abomination you created, and that you will have to deal with tomorrow. If your children asked you what do you for living, would like them to see this?