2424import java .time .Duration ;
2525import java .util .Set ;
2626import java .util .concurrent .CancellationException ;
27- import java .util .concurrent .CompletableFuture ;
2827import java .util .concurrent .CompletionException ;
2928import java .util .concurrent .CompletionStage ;
3029import java .util .concurrent .ExecutionException ;
@@ -136,14 +135,15 @@ default Promise<T> delay(Duration duration, boolean delayOnError) {
136135 .unwrap ()
137136 );
138137 }
139- CompletableFuture <Try <? super T >> delayed = new CompletableFuture <>();
140- whenComplete (Timeouts .configureDelay (this , delayed , duration , delayOnError ));
141- return this .dependent ()
142- .handle (Try .lift (), false )
143- // Use *Async to execute on default "this" executor
144- .thenCombineAsync (delayed , selectFirst (), PromiseOrigin .ALL )
145- .thenCompose (Try ::asPromise , true )
146- .unwrap ();
138+ DependentPromise <Try <T >> h = dependent ().handle (Try .lift (), false );
139+ return h .thenCompose (t -> t .isSuccess () || !(isCancelled () || t .isCancel ()) ?
140+ // "this" is already completed promise here (in both cases)
141+ // Use *Async to execute on default "this" executor
142+ h .thenCombineAsync (Timeouts .delay (duration ), (_1 , _2 ) -> join (), PromiseOrigin .PARAM_ONLY )
143+ :
144+ this ,
145+ true
146+ ).unwrap ();
147147 }
148148
149149 default Promise <T > orTimeout (long timeout , TimeUnit unit ) {
@@ -167,7 +167,7 @@ default Promise<T> orTimeout(Duration duration, boolean cancelOnTimeout) {
167167 .applyToEitherAsync (onTimeout , v -> Try .doneOrTimeout (v , duration ), PromiseOrigin .ALL )
168168 .thenCompose (Try ::asPromise , true );
169169
170- result .whenComplete (Timeouts .timeoutsCleanup (this , onTimeout , cancelOnTimeout ));
170+ result .whenComplete (PromiseHelper .timeoutsCleanup (this , onTimeout , cancelOnTimeout ));
171171 return result .unwrap ();
172172 }
173173
@@ -192,7 +192,7 @@ default Promise<T> onTimeout(T value, Duration duration, boolean cancelOnTimeout
192192 .applyToEitherAsync (onTimeout , Function .identity (), PromiseOrigin .ALL )
193193 .thenCompose (Try ::asPromise , true );
194194
195- result .whenComplete (Timeouts .timeoutsCleanup (this , onTimeout , cancelOnTimeout ));
195+ result .whenComplete (PromiseHelper .timeoutsCleanup (this , onTimeout , cancelOnTimeout ));
196196 return result .unwrap ();
197197 }
198198
@@ -220,7 +220,7 @@ default Promise<T> onTimeout(Supplier<? extends T> supplier, Duration duration,
220220 .applyToEitherAsync (onTimeout , Supplier ::get , PromiseOrigin .ALL )
221221 .thenCompose (Try ::asPromise , true );
222222
223- result .whenComplete (Timeouts .timeoutsCleanup (this , onTimeout , cancelOnTimeout ));
223+ result .whenComplete (PromiseHelper .timeoutsCleanup (this , onTimeout , cancelOnTimeout ));
224224 return result .unwrap ();
225225 }
226226
0 commit comments