1 package org.eclipse.aether.named.support;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.concurrent.Callable;
23 import java.util.concurrent.TimeUnit;
24 import java.util.function.Predicate;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29
30
31
32
33
34
35
36
37
38 public final class Retry
39 {
40 private static final Logger LOGGER = LoggerFactory.getLogger( Retry.class );
41
42 private Retry()
43 {
44
45 }
46
47
48
49
50
51
52
53
54 public static <R> R retry( final long time,
55 final TimeUnit unit,
56 final long sleepMillis,
57 final Callable<R> operation,
58 final Predicate<Exception> retryPredicate,
59 final R defaultResult ) throws InterruptedException
60 {
61 long now = System.nanoTime();
62 final long barrier = now + unit.toNanos( time );
63 int attempt = 1;
64 R result = null;
65 while ( now < barrier && result == null )
66 {
67 try
68 {
69 result = operation.call();
70 if ( result == null )
71 {
72 LOGGER.trace( "Retry attempt {}: no result", attempt );
73 Thread.sleep( sleepMillis );
74 }
75 }
76 catch ( InterruptedException e )
77 {
78 throw e;
79 }
80 catch ( Exception e )
81 {
82 LOGGER.trace( "Retry attempt {}: operation failure", attempt, e );
83 if ( retryPredicate != null && !retryPredicate.test( e ) )
84 {
85 throw new IllegalStateException( e );
86 }
87 }
88 now = System.nanoTime();
89 attempt++;
90 }
91 return result == null ? defaultResult : result;
92 }
93
94
95
96
97
98
99
100
101
102
103
104 public static <R> R retry( final int attempts,
105 final long sleepMillis,
106 final Callable<R> operation,
107 final Predicate<Exception> retryPredicate,
108 final R defaultResult ) throws InterruptedException
109 {
110 int attempt = 1;
111 R result = null;
112 while ( attempt <= attempts && result == null )
113 {
114 try
115 {
116 result = operation.call();
117 if ( result == null )
118 {
119 LOGGER.trace( "Retry attempt {}: no result", attempt );
120 Thread.sleep( sleepMillis );
121 }
122 }
123 catch ( InterruptedException e )
124 {
125 throw e;
126 }
127 catch ( Exception e )
128 {
129 LOGGER.trace( "Retry attempt {}: operation failure", attempt, e );
130 if ( retryPredicate != null && !retryPredicate.test( e ) )
131 {
132 throw new IllegalStateException( e );
133 }
134 }
135 attempt++;
136 }
137 return result == null ? defaultResult : result;
138 }
139 }