Reactive Programming with AWT / Swing

Reactive programming is rather popular these days, as it makes it pretty simple to express complex event flows – much better than using lots of manual programming with threads, listeners and concurrency APIs. Also, it combines the conciseness of fluent programming style with the power of modern multi-core CPUs. Even when not using a special library like RxJava, you can just use Java 8’s CompletableFuture to get started with reactive programming.

But what if you need to use AWT / Swing APIs with their special threading conditions?

Don’t panic, the solution is pretty simple, and rather straightforward. CompletableFuture allows you to specify an Executor that will do all the work in the end. And as Executor is just an interface, you can implement it any way you like – even using AWT / Swing APIs. Unless specified, a default thread pool will be used by CompletableFuture, but this is not what we want. We need an AWT / Swing Executor. But where to get it from? Well, Executor is a functional API, so thanks to Java 8’s method handles, things are pretty simple…:

static final Executor AWT = runnable -> {
  if (EventQueue.isDispatchThread())
    runnable.run();
  else
    EventQueue.invokeLater(runnable);
};

CompletableFuture.supplyAsync(..., AWT)...

Ain’t that neat? The same will certainly work for Swing API:

static final Executor SWING = runnable -> {
  if (SwingUtilities.isEventDispatchThread())
    runnable.run();
  else
    SwingUtilities.invokeLater(runnable);
};

CompletableFuture.supplyAsync(..., SWING)...

This proofs that it makes pretty much sense to use modern APIs even with old technology – and might help maintain existing applications a bit longer by partial code reduction using new Java 8 code constructs.

An example might be getting rid of that complex SwingWorker class, as the following does the same for most use cases, but is simpler to read and write:

CompletableFuture.supplyAsync(...).thenAcceptAsync(..., SWING);
Advertisements

About Markus Karg

Java Guru with +30 years of experience in professional software development. I travelled the whole world of IT, starting from Sinclair's great ZX Spectrum 48K, Commodore's 4040, over S/370, PCs since legendary XT, CP/M, VM/ESA, DOS, Windows (remember 3.1?), OS/2 WARP, Linux to Android and iOS... and still coding is my passion, and Java is my favourite drug!
This entry was posted in Java, Programming and tagged , , . Bookmark the permalink.