1 package org.eclipse.aether.util.concurrency;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import static java.util.Objects.requireNonNull;
23
24 import java.util.concurrent.atomic.AtomicInteger;
25 import java.util.concurrent.atomic.AtomicReference;
26 import java.util.concurrent.locks.LockSupport;
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public final class RunnableErrorForwarder
42 {
43
44 private final Thread thread = Thread.currentThread();
45
46 private final AtomicInteger counter = new AtomicInteger();
47
48 private final AtomicReference<Throwable> error = new AtomicReference<>();
49
50
51
52
53 public RunnableErrorForwarder()
54 {
55 }
56
57
58
59
60
61
62
63 public Runnable wrap( final Runnable runnable )
64 {
65 requireNonNull( runnable, "runnable cannot be null" );
66
67 counter.incrementAndGet();
68
69 return () ->
70 {
71 try
72 {
73 runnable.run();
74 }
75 catch ( RuntimeException | Error e )
76 {
77 error.compareAndSet( null, e );
78 throw e;
79 }
80 finally
81 {
82 counter.decrementAndGet();
83 LockSupport.unpark( thread );
84 }
85 };
86 }
87
88
89
90
91
92
93
94 public void await()
95 {
96 awaitTerminationOfAllRunnables();
97
98 Throwable error = this.error.get();
99 if ( error != null )
100 {
101 if ( error instanceof RuntimeException )
102 {
103 throw (RuntimeException) error;
104 }
105 else if ( error instanceof ThreadDeath )
106 {
107 throw new IllegalStateException( error );
108 }
109 else if ( error instanceof Error )
110 {
111 throw (Error) error;
112 }
113 throw new IllegalStateException( error );
114 }
115 }
116
117 private void awaitTerminationOfAllRunnables()
118 {
119 if ( !thread.equals( Thread.currentThread() ) )
120 {
121 throw new IllegalStateException( "wrong caller thread, expected " + thread + " and not "
122 + Thread.currentThread() );
123 }
124
125 boolean interrupted = false;
126
127 while ( counter.get() > 0 )
128 {
129 LockSupport.park();
130
131 if ( Thread.interrupted() )
132 {
133 interrupted = true;
134 }
135 }
136
137 if ( interrupted )
138 {
139 Thread.currentThread().interrupt();
140 }
141 }
142
143 }