1

I want to execute a method (that doesn't return anything, just clean up things) asynchronously in the single thread in Java. Kindly let me know how to do that.

7
  • 2
    There's really no such thing in standard Java. You'll need another thread (from somewhere, possibly from the common pool). Commented Jun 4, 2020 at 13:07
  • 2
    Why exactly are you wanting to do this on "the single thread"? Commented Jun 4, 2020 at 13:17
  • I am using a framework which is not thread-safe. Hence, I want it to execute on single thread asynchronously Commented Jun 4, 2020 at 13:22
  • 4
    “single thread” and “asynchronously” is a contradiction. Commented Jun 4, 2020 at 13:24
  • 2
    That’s just a name. These async function either run deferred (at a later time in the same thread, which is not asynchronous) or are settling on a promise encapsulating the truly asynchronous operation implemented by the browser (using threads behind the scenes). Having your callbacks executed in the same thread only works when the particular thread implements an event loop, like the browser does. With the AWT event handling thread, such a behavior is possible. Same for the sole worker thread of a single threaded executor. But not for an arbitrary thread, as it doesn’t execute such a loop. Commented Jun 4, 2020 at 16:24

2 Answers 2

2

Java 8 introduced CompletableFuture in java.util.concurrent.CompletableFuture, can be used to make a asynch call :

 CompletableFuture.runAsync(() -> { // method call or code to be asynch. }); 
Sign up to request clarification or add additional context in comments.

4 Comments

I think it creates a new thread internally for the same. Isn't it?
yes under the hood it creates a new thread but the whole idea of asynchronous execution defies a single thread environment
Is it so? As far as I know JS uses single-thread asynchronous execution. So it might be possible.
JS has a special engine Web API handle these tasks in the background for JS. The call stack recognizes functions of the Web API and hands them off to be handled by the browser. Once those tasks are finished by the browser, they return and are pushed onto the stack as a callback.
1

Oh nice, this is a good example for Future<T>

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future and return null as a result of the underlying task.
Source: JavaDoc

Here is a really simple working example to achieve what you are asking for

// Using Lambda Expression Future<Void> future = CompletableFuture.runAsync(() -> { // Simulate a long-running Job try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new IllegalStateException(e); } System.out.println("I'll run in a separate thread than the main thread."); }); // Start the future task without blocking main thread future.get() 

Under the hoods it's still another thread, just to clarify it

4 Comments

"[...] asynchronously on same thread [...]", this is the essential part of the question. Thus, your answer is unfortunately not answering the OP's question.
Sometime it may happen that the OP is not completely into Java and sometime he may ask a particular question like this because he doesn't want to deal with native Thread implementation. I have provided an answer which does what he asks in a simpler manner than raw Thread implementation, clearly there is no way in Java to do it without using Threads as @Kayaman stated.
I know we have all these options, that's why I have specifically said in the question "same thread". So, do you have any solution for that? @Snix
Java doesn't work like that as @Kayaman stated. I don't think you can do that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.