Skip to content

Instantly share code, notes, and snippets.

@mmubasher
Created September 19, 2022 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmubasher/699d90d376849559a629eb9417f4cc3f to your computer and use it in GitHub Desktop.
Save mmubasher/699d90d376849559a629eb9417f4cc3f to your computer and use it in GitHub Desktop.
This gist demos the working of a known number of Async tasks handled with completeable futures and hashmap
package com.example.futures;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
@SpringBootApplication
public class FuturesDemoApplication {
public static void main(String[] args) {
SpringApplication.run(FuturesDemoApplication.class, args);
CompletableFuture<HashMap<String, String>> hashMapCompletableFuture = getCompletableFutures();
hashMapCompletableFuture.thenApplyAsync((t) -> {
System.out.println(t.get("2"));
System.out.println("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-");
System.out.println(t.get("1"));
return null;
});
}
public static CompletableFuture<HashMap<String, String>> getCompletableFutures() {
final HashMap<String, String> myHashMap = new HashMap<>();
CompletableFuture<String> firstAsync =
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
return "First Async Resolved";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
CompletableFuture<String> secondAsync =
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(300);
return "Second Async Resolved";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
return CompletableFuture.allOf(
firstAsync,
secondAsync
)
.thenApplyAsync(ignored -> {
myHashMap.put("1", firstAsync.join());
myHashMap.put("2", secondAsync.join());
return myHashMap;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment