Tuesday, 8 September 2009

JavaFX Week 3 - Async

The JavaPassion JavaFX slides this week are mostly a repeat of the binding slides previously seen, so it felt like a quick recap - which is always welcome! The resources were a very interesting read, in summary they were:

Background tasks in JavaFX - A good article on binding variables to the user interface and discusses the fact JavaFX1.2 is single-threaded and how to deal with writing to variables from a background thread.  One comment highlights a bug in JavaFX 1.2, where the percentDone from a Task is returning 0..100 instead of 0..1 - something to bear in mind.

JavaFX 1.2 Async blog by Baechul - Well worth reading, although it might be a bit heavy for a newbie to JavaFX, especially if they haven't done Java before. I've created a class diagram that acts as a summary of this blog because I found it so useful as an overview...

And a version with comments (but I'm not convinced that they will be readable)...

Basically there seems to be some rules to follow, they seem similar to Swing

(Thank you philho for correcting my post in your comments!)

  • You must update the user interface components from the EDT (event dispatch thread)

  • User interface stuff happens on the EDT, so you can use the javafx.lang.FX.deferAction class to post actions to the UI thread (Presumaly this is similar to SwingUtilities.invokeLater).

  • Typically you implement the RunnableFuture interface in one class, then extend JavaTaskBase in another class.  The JavaTaskBase class has a create method that you override to create your RunnableFuture instance.

Jim Weavers JavaFX Blog - shows an example where you can start multiple threads and cancel them, with a user interface showing the progress of each thread.

What seems very clean is that the JavaFX API also uses the thread classes identified above, so for example,HttpRequest extends JavaTaskBase.  Some user interface controls take advantage of this, notibly the ProgressBar integrates nicely with the JavaTaskBase class.  This means that as data is transferred using the HttpRequest object, the ProgressBar can be set up to automatically update to show the progress!

Interestingly you are limited to eight threads running in parallel in JavaFX, this sounds a little limiting.

I hope some of that is interesting for you.



  1. Unless I am mistaken, you got it reversed. I think you have to update the GUI on the EDT, actually.
    See for example Debugging Swing article for a summary.

    I appreciate your UML diagrams. The second is readable once saved on disk and zoomed in with a good image viewer...

  2. "The Swing framework manages component drawing, updates, and event handlers on the EDT", so you're absolutely right - I'll modify the text in the post straight away, but probably leave the images for now.

    Thanks for pointing out the error - much appreciated.

    SpikyOrange - logged in as someone else ;-)