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.
Asked
Active
Viewed 2,243 times
1
-
2There's really [no such thing](https://stackoverflow.com/questions/2846664/implementing-coroutines-in-java) in standard Java. You'll need another thread (from somewhere, possibly from the common pool). – Kayaman Jun 04 '20 at 13:07
-
2Why exactly are you wanting to do this on "the single thread"? – chrylis -cautiouslyoptimistic- Jun 04 '20 at 13:17
-
I am using a framework which is not thread-safe. Hence, I want it to execute on single thread asynchronously – raman bhadauria Jun 04 '20 at 13:22
-
4“single thread” and “asynchronously” is a contradiction. – Holger Jun 04 '20 at 13:24
-
Is it so @Holger ? As far as I know JS uses single-thread asynchronous execution. So it might be possible in Java too. – raman bhadauria Jun 04 '20 at 15:51
-
2That’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. – Holger Jun 04 '20 at 16:24
-
There is no "the single thread in Java". There is the starting thread, which is in no way better or worse than others. Anyway, you can program in Java in Javascript style, though I do no see much sense in this. You need to convert the starting thread in a ScheduledExecutorService and submit methods to it so they execute asynchronously. In fact, calling that methods directly is faster and simpler. – Alexei Kaigorodov Jun 04 '20 at 19:44
2 Answers
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.
});

Sambit Nag
- 38
- 5
-
I think it creates a new thread internally for the same. Isn't it? – raman bhadauria Jun 04 '20 at 13:19
-
yes under the hood it creates a new thread but the whole idea of asynchronous execution defies a single thread environment – Sambit Nag Jun 04 '20 at 13:30
-
Is it so? As far as I know JS uses single-thread asynchronous execution. So it might be possible. – raman bhadauria Jun 04 '20 at 15:50
-
1JS 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. – Sambit Nag Jun 04 '20 at 16:35
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

Snix
- 541
- 4
- 12
-
*"[...] asynchronously on same thread [...]"*, this is the essential part of the question. Thus, your answer is unfortunately not answering the OP's question. – akuzminykh Jun 04 '20 at 13:11
-
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. – Snix Jun 04 '20 at 13:15
-
1I 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 – raman bhadauria Jun 04 '20 at 13:20
-
Java doesn't work like that as @Kayaman stated. I don't think you can do that. – Snix Jun 04 '20 at 13:23