I have been doing some research on this but I am still VERY confused to say the least.
Can anyone give me a concrete example of when to use Task
and when to use Platform.runLater(Runnable);
? What exactly is the difference? Is there a golden rule to when to use any of these?
Also correct me if I'm wrong but aren't these two "Objects" a way of creating another thread inside the main thread in a GUI (used for updating the GUI)?
One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():
In UI thread also known as the JavaFX Application thread:
in Service implementation (background worker):
Platform.runLater
: If you need to update a GUI component from a non-GUI thread, you can use that to put your update in a queue and it will be handle by the GUI thread as soon as possible.Task
implements theWorker
interface which is used when you need to run a long task outside the GUI thread (to avoid freezing your application) but still need to interact with the GUI at some stage.If you are familiar with Swing, the former is equivalent to
SwingUtilities.invokeLater
and the latter to the concept ofSwingWorker
.The javadoc of Task gives many examples which should clarify how they can be used. You can also refer to the tutorial on concurrency.
It can now be changed to lambda version
Use
Platform.runLater(...)
for quick and simple operations andTask
for complex and big operations .Platform.runLater(...)
Task
: Task Example in Ensemble AppExample: Why Can't we use
Platform.runLater(...)
for long calculations (Taken from below reference).Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.
Code using
Platform.runLater(...)
:Code using Task :
Reference : Worker Threading in JavaFX 2.0