1616
1717package software .amazon .cloudwatchlogs .emf .environment ;
1818
19+ import java .util .ArrayList ;
20+ import java .util .List ;
1921import java .util .Optional ;
2022import java .util .concurrent .CompletableFuture ;
2123import lombok .AllArgsConstructor ;
@@ -49,18 +51,15 @@ public CompletableFuture<Environment> resolveEnvironment() {
4951 return CompletableFuture .completedFuture (cachedEnvironment );
5052 }
5153
52- CompletableFuture <Optional <EnvironmentResolveResult >> resolvedEnv =
53- discoverEnvironmentAsync ();
54+ CompletableFuture <Optional <Environment >> resolvedEnv = discoverEnvironmentAsync ();
5455
5556 return resolvedEnv .thenApply (
5657 optionalEnv ->
57- optionalEnv
58- .map (EnvironmentResolveResult ::getEnvironment )
59- .orElseGet (
60- () -> {
61- cachedEnvironment = defaultEnvironment ;
62- return cachedEnvironment ;
63- }));
58+ optionalEnv .orElseGet (
59+ () -> {
60+ cachedEnvironment = defaultEnvironment ;
61+ return cachedEnvironment ;
62+ }));
6463 }
6564
6665 public Environment getDefaultEnvironment () {
@@ -72,28 +71,30 @@ void cleanResolvedEnvironment() {
7271 cachedEnvironment = null ;
7372 }
7473
75- private CompletableFuture <Optional <EnvironmentResolveResult >> discoverEnvironmentAsync () {
74+ private CompletableFuture <Optional <Environment >> discoverEnvironmentAsync () {
7675
77- CompletableFuture <Optional <EnvironmentResolveResult >> ans =
78- CompletableFuture .completedFuture (Optional .empty ());
76+ CompletableFuture <Optional <Environment >> ans = new CompletableFuture <>();
77+
78+ List <CompletableFuture <EnvironmentResolveResult >> futures = new ArrayList <>();
7979 for (Environment env : environments ) {
8080 CompletableFuture <EnvironmentResolveResult > future =
8181 CompletableFuture .supplyAsync (
8282 () -> new EnvironmentResolveResult (env .probe (), env ));
83- ans =
84- ans .thenCombine (
85- future ,
86- (optionalEnv , envResult ) -> {
87- if (optionalEnv .isPresent ()) {
88- return optionalEnv ;
89- }
90- if (envResult .isCandidate ) {
91- return Optional .of (envResult );
92- }
93- return Optional .empty ();
94- });
83+ futures .add (future );
9584 }
9685
86+ CompletableFuture .runAsync (
87+ () -> {
88+ for (CompletableFuture <EnvironmentResolveResult > future : futures ) {
89+ EnvironmentResolveResult result = future .join ();
90+ if (result .isCandidate ) {
91+ ans .complete (Optional .of (result .environment ));
92+ return ;
93+ }
94+ }
95+ ans .complete (Optional .empty ());
96+ });
97+
9798 return ans ;
9899 }
99100
0 commit comments