Reputation: 155
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.
Upvotes: 1
Views: 3353
Reputation: 48
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.
});
Upvotes: 2
Reputation: 541
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
Upvotes: 1