Guillaume F.
Guillaume F.

Reputation: 1130

Is code run from Platform.runLater thread safe?

If I have code ran entirely from within Platform.runLater, is that code automatically thread safe?

My understanding is that code ran on Platform.runLater is ran on the JavaFX application thread, which there is only one.

For example if I manipulate an hash map entirely in Plaform.runLater, I don't have to worry about multiple threads, right?

Upvotes: 0

Views: 586

Answers (1)

Slaw
Slaw

Reputation: 45806

Whether or not using Platform#runLater(Runnable) is thread-safe is entirely dependent on how you use it. The example you give is you have a Map visible from a background thread but only ever manipulate it on the JavaFX Application Thread via runLater. Maybe something like:

// executing on background thread
Object newKey = ...;
Object newVal = ...;
Platform.runLater(() -> map.put(newKey, newVal));

This makes the Map "thread-safe" only from the point-of-view of the JavaFX Application Thread. If the background thread later attempts to read the Map (e.g. map.get(newKey)) there is no guarantee said thread will see the new entry. In other words, it may read null because the entry "doesn't exist" or it may read an old value if one was already present. You could of course fix this by reading on the JavaFX Application Thread as well:

Object val = CompletableFuture.supplyAsync(() -> map.get(key), Platform::runLater).join();

Or even by waiting for the JavaFX Application Thread to finish writing to the Map:

CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(() -> {
    // write to map
    latch.countDown();
});
latch.await();
// writes to map will be visible to background thread from here

That said, actions by the background thread that happened before the call to runLater will be visible to the JavaFX Application Thread. In other words, a happens-before relationship is created. When scheduling the Runnable to execute on the JavaFX Application Thread eventually some inter-thread communication must occur, which in turn requires synchronization in order to be thread-safe. Looking at the Windows implementation of JavaFX I can't say for certain what this synchronization looks like, however, because it appears to invoke a native method.

Upvotes: 3

Related Questions