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