Java – Execute asynchronous lambda in the main thread?

Execute asynchronous lambda in the main thread?… here is a solution to the problem.

Execute asynchronous lambda in the main thread?

I have some asynchronous code in my project that executes a lambda that takes a few seconds to run and another lambda when the first lambda completes. Kind of like this :

CompletableFuture.supplyAsync(() -> {
    return longExecution("Hello Test");
}).thenAccept(text -> {
    mustBeInMainThread(text);
});

Now this is just an example. But I need thenAccept lambda execution to happen in the main thread, not in a separate thread.

Is this possible, and if so, how can I achieve it?

Solution

You can’t tell it to run in the main thread using the constructs of the future, but you can get the result and use it:

CompletableFuture<MyObject> future = 
        CompletableFuture.supplyAsync(() -> longExecution("Hello Test"));

do other things in main thread while async task runs

You can then use the result in the main thread by waiting:

//get result and call method in main thread:
mustBeInMainThread(future.join());

Related Problems and Solutions