-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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