Home > database >  CompletableFuture waiting for UI-thread from UI-thread?
CompletableFuture waiting for UI-thread from UI-thread?

Time:05-27

Java 8's promise implementation, namely CompletableFuture, provides both thenApply(...) and get() methods.

Where get() waits if necessary for the promise to complete, and then returns its result.


Now assume we use thenApply(...) (or thenApplyAsync(...)) to chain some code to run on UI-thread
(see stackoverflow.com/difference between thenApply and thenApplyAsync).

What is the behaviour if we call get() in the UI-thread as well, like does Java handle this case somehow, or can it result to a so-called dead-lock or infinite-loop?


I previously was using Qt framework, where depending on how we did implement waiter (dispatch-UI-events vs sleep), it was possible to wait for UI-thread from within same UI-thread (for example, the entire view came back to live, and that without returning from my code).
But I am not sure if Java even supports that.

CodePudding user response:

Calling get() blocks the current thread until the result is available. If that's the UI event dispatcher thread then your application's UI becomes unresponsive (blocked).

And unlike Qt, Java does not support manually processing the UI events, meaning once you wait on the UI-thread nothing else can run on UI-thread (until waiter returns).


In addition, don't hack "thenApply(...)" method to run things on UI-thread, as there's a better solution, I mean use the thenApplyAsync(...) version which takes an Executor as parameter. Said Executor is a functional interface with one method, void execute(Runnable command). You can use EventQueue::invokeLater (or its wrapper SwingUtilities.invokeLater) for that. It will then execute the code on the event dispatcher thread (aka UI-thread).

  • Related