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<Throwable>();
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 new Runnable()
70 {
71 public void run()
72 {
73 try
74 {
75 runnable.run();
76 }
77 catch ( RuntimeException e )
78 {
79 error.compareAndSet( null, e );
80 throw e;
81 }
82 catch ( Error e )
83 {
84 error.compareAndSet( null, e );
85 throw e;
86 }
87 finally
88 {
89 counter.decrementAndGet();
90 LockSupport.unpark( thread );
91 }
92 }
93 };
94 }
95
96
97
98
99
100
101
102 public void await()
103 {
104 awaitTerminationOfAllRunnables();
105
106 Throwable error = this.error.get();
107 if ( error != null )
108 {
109 if ( error instanceof RuntimeException )
110 {
111 throw (RuntimeException) error;
112 }
113 else if ( error instanceof ThreadDeath )
114 {
115 throw new IllegalStateException( error );
116 }
117 else if ( error instanceof Error )
118 {
119 throw (Error) error;
120 }
121 throw new IllegalStateException( error );
122 }
123 }
124
125 private void awaitTerminationOfAllRunnables()
126 {
127 if ( !thread.equals( Thread.currentThread() ) )
128 {
129 throw new IllegalStateException( "wrong caller thread, expected " + thread + " and not "
130 + Thread.currentThread() );
131 }
132
133 boolean interrupted = false;
134
135 while ( counter.get() > 0 )
136 {
137 LockSupport.park();
138
139 if ( Thread.interrupted() )
140 {
141 interrupted = true;
142 }
143 }
144
145 if ( interrupted )
146 {
147 Thread.currentThread().interrupt();
148 }
149 }
150
151 }