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.
- 2There's really no such thing in standard Java. You'll need another thread (from somewhere, possibly from the common pool).Kayaman– Kayaman2020-06-04 13:07:51 +00:00Commented Jun 4, 2020 at 13:07
- 2Why exactly are you wanting to do this on "the single thread"?chrylis -cautiouslyoptimistic-– chrylis -cautiouslyoptimistic-2020-06-04 13:17:13 +00:00Commented 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 asynchronouslyraman bhadauria– raman bhadauria2020-06-04 13:22:37 +00:00Commented Jun 4, 2020 at 13:22
- 4“single thread” and “asynchronously” is a contradiction.Holger– Holger2020-06-04 13:24:27 +00:00Commented Jun 4, 2020 at 13:24
- 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– Holger2020-06-04 16:24:35 +00:00Commented Jun 4, 2020 at 16:24
2 Answers
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. }); 4 Comments
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