/
ThreadedStreamConsumer.java
338 lines (291 loc) · 9.41 KB
/
ThreadedStreamConsumer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package org.apache.maven.plugin.surefire.booterclient.output;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.surefire.api.event.Event;
import org.apache.maven.surefire.extensions.EventHandler;
import javax.annotation.Nonnull;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThread;
/**
* Knows how to reconstruct *all* the state transmitted over Channel by the forked process.
* <br>
* After applying the performance improvements with {@link QueueSynchronizer} the throughput becomes
* 6.33 mega messages per second
* (158 nano seconds per message, 5 million messages within 0.79 seconds - see the test ThreadedStreamConsumerTest)
* on CPU i5 Dual Core 2.6 GHz and Oracle JDK 11.
*
* @author Kristian Rosenvold
*/
public final class ThreadedStreamConsumer
implements EventHandler<Event>, Closeable
{
private static final int QUEUE_MAX_ITEMS = 10_000;
private static final Event END_ITEM = new FinalEvent();
private final QueueSynchronizer<Event> synchronizer = new QueueSynchronizer<>( QUEUE_MAX_ITEMS, END_ITEM );
private final AtomicBoolean stop = new AtomicBoolean();
private final AtomicBoolean isAlive = new AtomicBoolean( true );
private final Pumper pumper;
final class Pumper
implements Runnable
{
private final EventHandler<Event> target;
private final MultipleFailureException errors = new MultipleFailureException();
Pumper( EventHandler<Event> target )
{
this.target = target;
}
/**
* Calls {@link ForkClient#handleEvent(Event)} which may throw any {@link RuntimeException}.<br>
* Even if {@link ForkClient} is not fault-tolerant, this method MUST be fault-tolerant and thus the
* try-catch block must be inside of the loop which prevents from loosing events from {@link EventHandler}.
* <br>
* If {@link org.apache.maven.plugin.surefire.report.ConsoleOutputFileReporter#writeTestOutput} throws
* {@link java.io.IOException} and then {@code target.consumeLine()} throws any RuntimeException, this method
* MUST NOT skip reading the events from the forked JVM; otherwise we could simply lost events
* e.g. acquire-next-test which means that {@link ForkClient} could hang on waiting for old test to complete
* and therefore the plugin could be permanently in progress.
*/
@Override
public void run()
{
while ( !stop.get() || !synchronizer.isEmptyQueue() )
{
try
{
Event item = synchronizer.awaitNext();
if ( shouldStopQueueing( item ) )
{
break;
}
target.handleEvent( item );
}
catch ( Throwable t )
{
// ensure the stack trace to be at the instance of the exception
t.getStackTrace();
errors.addException( t );
}
}
isAlive.set( false );
}
boolean hasErrors()
{
return errors.hasNestedExceptions();
}
void throwErrors() throws IOException
{
throw errors;
}
}
public ThreadedStreamConsumer( EventHandler<Event> target )
{
pumper = new Pumper( target );
Thread thread = newDaemonThread( pumper, "ThreadedStreamConsumer" );
thread.start();
}
@Override
public void handleEvent( @Nonnull Event event )
{
if ( stop.get() )
{
return;
}
// Do NOT call Thread.isAlive() - slow.
// It makes worse performance from 790 millis to 1250 millis for 5 million messages.
else if ( !isAlive.get() )
{
synchronizer.clearQueue();
return;
}
synchronizer.pushNext( event );
}
@Override
public void close()
throws IOException
{
if ( stop.compareAndSet( false, true ) )
{
synchronizer.markStopped();
}
if ( pumper.hasErrors() )
{
pumper.throwErrors();
}
}
/**
* Compared item with {@link #END_ITEM} by identity.
*
* @param item element from <code>items</code>
* @return {@code true} if tail of the queue
*/
private static boolean shouldStopQueueing( Event item )
{
return item == END_ITEM;
}
/**
*
*/
private static class FinalEvent extends Event
{
FinalEvent()
{
super( null );
}
@Override
public boolean isControlCategory()
{
return false;
}
@Override
public boolean isConsoleCategory()
{
return false;
}
@Override
public boolean isConsoleErrorCategory()
{
return false;
}
@Override
public boolean isStandardStreamCategory()
{
return false;
}
@Override
public boolean isSysPropCategory()
{
return false;
}
@Override
public boolean isTestCategory()
{
return false;
}
@Override
public boolean isJvmExitError()
{
return false;
}
}
/**
* This synchronization helper mostly avoids the locks.
* If the queue size has reached zero or {@code maxQueueSize} then the threads are locked (parked/unparked).
* The thread instance T1 is reader (see the class "Pumper") and T2 is the writer (see the method "handleEvent").
*
* @param <T> element type in the queue
*/
static class QueueSynchronizer<T>
{
private final SyncT1 t1 = new SyncT1();
private final SyncT2 t2 = new SyncT2();
private final ConcurrentLinkedDeque<T> queue = new ConcurrentLinkedDeque<>();
private final AtomicInteger queueSize = new AtomicInteger();
private final int maxQueueSize;
private final T stopItemMarker;
QueueSynchronizer( int maxQueueSize, T stopItemMarker )
{
this.maxQueueSize = maxQueueSize;
this.stopItemMarker = stopItemMarker;
}
private class SyncT1 extends AbstractQueuedSynchronizer
{
private static final long serialVersionUID = 1L;
@Override
protected int tryAcquireShared( int arg )
{
return queueSize.get() == 0 ? -1 : 1;
}
@Override
protected boolean tryReleaseShared( int arg )
{
return true;
}
void waitIfZero() throws InterruptedException
{
acquireSharedInterruptibly( 1 );
}
void release()
{
releaseShared( 0 );
}
}
private class SyncT2 extends AbstractQueuedSynchronizer
{
private static final long serialVersionUID = 1L;
@Override
protected int tryAcquireShared( int arg )
{
return queueSize.get() < maxQueueSize ? 1 : -1;
}
@Override
protected boolean tryReleaseShared( int arg )
{
return true;
}
void awaitMax()
{
acquireShared( 1 );
}
void tryRelease()
{
if ( queueSize.get() == 0 )
{
releaseShared( 0 );
}
}
}
void markStopped()
{
addNext( stopItemMarker );
}
void pushNext( T t )
{
t2.awaitMax();
addNext( t );
}
T awaitNext() throws InterruptedException
{
t2.tryRelease();
t1.waitIfZero();
queueSize.decrementAndGet();
return queue.pollFirst();
}
boolean isEmptyQueue()
{
return queue.isEmpty();
}
void clearQueue()
{
queue.clear();
}
private void addNext( T t )
{
queue.addLast( t );
if ( queueSize.getAndIncrement() == 0 )
{
t1.release();
}
}
}
}