How to Asynchronously Call a Method in Java

How to call a method and run it asynchronously?

You can divide your loop of users creation into smaller loops, and run them in parallel. Consider this example, which runs 4 times faster :

public static void main(String[] args) {
// create a pool executor of 4 threads, increase or decrease it if need
Executor executor = Executors.newFixedThreadPool(4);

CompletableFuture<List<User>> future1 = CompletableFuture.supplyAsync(() -> getUsers(25), executor);
CompletableFuture<List<User>> future2 = CompletableFuture.supplyAsync(() -> getUsers(25), executor);
CompletableFuture<List<User>> future3 = CompletableFuture.supplyAsync(() -> getUsers(25), executor);
CompletableFuture<List<User>> future4 = CompletableFuture.supplyAsync(() -> getUsers(25), executor);

List<User> allUsers = Stream.of(future1, future2, future3, future4)
.map(CompletableFuture::join)
.flatMap(List::stream)
.collect(Collectors.toList());
}

public static List<User> getUsers(int count) {
List<User> users = new ArrayList<>();
for (int i = 0; i < count; i++) {
users.add(new User("someName", "someAge"));
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return users;
}

Java asynchronously call a method for target output

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

Future<Boolean> future = CompletableFuture.runAsync(() -> {
// Do your checks, if true, just return this future
System.out.println("I'll run in a separate thread than the main thread.");
});

// Now, you may want to block the main thread waiting for the result
while(!future.isDone()) {
// Meanwhile, you can do others stuff
System.out.println("Doing other stuff or simply waiting...");
}

// When future.isDone() returns, you will be able to retrieve the result
Boolean result = future.get();

I need not wait until executing async method call()

The main thread is blocked on the call to future.get() until the task completes. Remove this call and your second log statement will print immediately.

That addresses what you asked exactly. But I doubt it is what you want.

The purpose of submitting an asynchronous task is to permit the main thread to carry on immediately with other work. If the main thread requires the result of the task to proceed, the task is not a candidate for performing asynchronously.

Instead, add the processing of the result to the asynchronous task itself. Then the main thread does not have to wait for the result.

Calling two Java methods asynchronously

I would try something simple, like CompletableFuture:

import java.util.concurrent.CompletableFuture;
...
final CompletableFuture<String> listOfCities = CompletableFuture.supplyAsync(() -> service.getListOfCities(...));
final CompletableFuture<String> listOfCountries = CompletableFuture.supplyAsync(() -> service. getListOfCountries(...));
final CompletableFuture<Void> allCompleted = CompletableFuture.allOf(listOfCities, listOfCountries);
allCompleted.thenRun(() -> {
// whatever you want to do
});

See these examples for reference.

Java Calling function from other class async

You have a syntax related issue immediately, which is new CandlestickDriver.run. This needs to be new CandlestickDriver().run as you're instantiating a new object.

Also, CompletableFuture#supplyAsync takes a Supplier<U> as input, and you're passing Supplier<void>, but void isn't a type that can be supplied. Since this function doesn't return anything, you don't need to supplyAsync, but rather runAsync.

CompletableFuture.runAsync(() -> new CandlestickDriver().run("", "", "", false, false));


Related Topics



Leave a reply



Submit