The best way to use scala Futures together with a single-threaded toolkit such as JavaFX would be to define an executor that allows you to execute futures or actors on the thread of the UI Toolkit.
The same problem exists for Swing, which also requires updates to happen on the swing thread. Viktor Klang came up with the following solution Swing Execution Context. Here it is translated for JavaFX:
import akka.dispatch.ExecutionContext
import javafx.application.Platform
import java.util.concurrent.Executor
//
object JavaFXExecutionContext {
implicit val javaFxExecutionContext: ExecutionContext = ExecutionContext.fromExecutor(new Executor {
def execute(command: Runnable): Unit = Platform.runLater(command)
})
}
You would use it like this:
// import the default ec
import scala.concurrent.ExecutionContext.Implicits.global
// define the JavaFX ec so we can use it explicitly
val fxec = JavaFXExecutionContext.javaFxExecutionContext
future {
// some asynchronous computation, running on the default
// ForkJoin ExecutionContext because no ec is passed
// explicitly
}.map(result => {
// update JavaFX components from result
// This will run in the JavaFX thread.
// Check Platform.isFxApplicationThread() to be sure!
})(fxec)
The pipeline of futures can be very complex, as long as the step(s) that interact with JavaFX components are all running on the JavaFX ExecutionContext.
Note: it is up to you whether you make the ForkJoin ec the default and pass the JavaFX ec explicitly or vice versa. It might be a good idea to make the JavaFX ec the default to prevent errors and mark the parts that can run asynchronously explicitly with the ForkJoin ec.
For integrating an Actor based system with a single-threaded UI toolkit there is also a solution. See Swing Actors. All you have to do is to replace the
SwingUtilities.invokeLater(command)
with
Platform.runLater(command)
and you're good to go!
If you have a big UI application and just want to spin off some asynchronous operations (loading a file or doing some computation), the futures-based approach is probably preferable. But be careful not to do any interaction (neither read nor write) with JavaFX components in the futures that run asynchronously on the default execution context.
If you have a large actor based system and just want to attach an UI to some parts, having a few actors that run on the JavaFX thread is probably preferable. YMMV.