11// SPDX-License-Identifier: BSD-2-Clause
22package org .xbill .DNS ;
33
4- import java .lang .reflect .InvocationTargetException ;
5- import java .lang .reflect .Method ;
64import java .time .Duration ;
75import java .util .ArrayDeque ;
86import java .util .Queue ;
97import java .util .concurrent .CompletableFuture ;
108import java .util .concurrent .CompletionStage ;
11- import java .util .concurrent .ScheduledFuture ;
12- import java .util .concurrent .ScheduledThreadPoolExecutor ;
139import java .util .concurrent .TimeUnit ;
14- import java .util .concurrent .TimeoutException ;
1510import lombok .extern .slf4j .Slf4j ;
1611
1712@ Slf4j
@@ -20,78 +15,6 @@ final class AsyncSemaphore {
2015 private final Permit singletonPermit = new Permit ();
2116 private volatile int permits ;
2217
23- private static class TimeoutCompletableFuture <T > extends CompletableFuture <T > {
24- private static final Method orTimeoutMethod ;
25-
26- static {
27- Method localOrTimeoutMethod ;
28- if (!System .getProperty ("java.version" ).startsWith ("1." )) {
29- try {
30- localOrTimeoutMethod =
31- CompletableFuture .class .getMethod ("orTimeout" , long .class , TimeUnit .class );
32- } catch (NoSuchMethodException e ) {
33- localOrTimeoutMethod = null ;
34- log .warn (
35- "CompletableFuture.orTimeout method not found in Java 9+, using custom implementation" ,
36- e );
37- }
38- } else {
39- localOrTimeoutMethod = null ;
40- }
41- orTimeoutMethod = localOrTimeoutMethod ;
42- }
43-
44- @ SuppressWarnings ("unchecked" )
45- public CompletableFuture <T > compatTimeout (long timeout , TimeUnit unit ) {
46- if (orTimeoutMethod == null ) {
47- return orTimeout (this , timeout , unit );
48- } else {
49- try {
50- return (CompletableFuture <T >) orTimeoutMethod .invoke (this , timeout , unit );
51- } catch (IllegalAccessException | InvocationTargetException e ) {
52- return orTimeout (this , timeout , unit );
53- }
54- }
55- }
56-
57- private static <T > CompletableFuture <T > orTimeout (
58- CompletableFuture <T > f , long timeout , TimeUnit unit ) {
59- ScheduledFuture <?> sf =
60- TimeoutScheduler .executor .schedule (
61- () -> {
62- if (!f .isDone ()) {
63- f .completeExceptionally (new TimeoutException ());
64- }
65- },
66- timeout ,
67- unit );
68- f .whenComplete (
69- (r , ex ) -> {
70- if (ex == null && !sf .isDone ()) {
71- sf .cancel (false );
72- }
73- });
74- return f ;
75- }
76-
77- private static final class TimeoutScheduler {
78- private static final ScheduledThreadPoolExecutor executor ;
79-
80- static {
81- executor =
82- new ScheduledThreadPoolExecutor (
83- 1 ,
84- r -> {
85- Thread t = new Thread (r );
86- t .setDaemon (true );
87- t .setName ("dnsjava AsyncSemaphoreTimeoutScheduler" );
88- return t ;
89- });
90- executor .setRemoveOnCancelPolicy (true );
91- }
92- }
93- }
94-
9518 final class Permit {
9619 public void release () {
9720 synchronized (queue ) {
0 commit comments