-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
DynamicTaskExecutor.java
263 lines (238 loc) · 8.47 KB
/
DynamicTaskExecutor.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
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.unsafe.impl.batchimport.executor;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.function.Supplier;
import org.neo4j.function.Suppliers;
import static java.lang.Integer.max;
import static java.lang.Integer.min;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.neo4j.helpers.Exceptions.launderedException;
/**
* Implementation of {@link TaskExecutor} with a maximum queue size and where each processor is a dedicated
* {@link Thread} pulling queued tasks and executing them.
*/
public class DynamicTaskExecutor<LOCAL> implements TaskExecutor<LOCAL>
{
public static final ParkStrategy DEFAULT_PARK_STRATEGY = new ParkStrategy.Park( 10, MILLISECONDS );
private final BlockingQueue<Task<LOCAL>> queue;
private final ParkStrategy parkStrategy;
private final String processorThreadNamePrefix;
@SuppressWarnings( "unchecked" )
private volatile Processor[] processors = (Processor[]) Array.newInstance( Processor.class, 0 );
private volatile boolean shutDown;
private volatile boolean abortQueued;
private volatile Throwable panic;
private final Supplier<LOCAL> initialLocalState;
private final int maxProcessorCount;
public DynamicTaskExecutor( int initialProcessorCount, int maxProcessorCount, int maxQueueSize,
ParkStrategy parkStrategy, String processorThreadNamePrefix )
{
this( initialProcessorCount, maxProcessorCount, maxQueueSize, parkStrategy, processorThreadNamePrefix,
Suppliers.<LOCAL>singleton( null ) );
}
public DynamicTaskExecutor( int initialProcessorCount, int maxProcessorCount, int maxQueueSize,
ParkStrategy parkStrategy, String processorThreadNamePrefix, Supplier<LOCAL> initialLocalState )
{
this.maxProcessorCount = maxProcessorCount == 0 ? Integer.MAX_VALUE : maxProcessorCount;
assert this.maxProcessorCount >= initialProcessorCount :
"Unexpected initial processor count " + initialProcessorCount + " for max " + maxProcessorCount;
this.parkStrategy = parkStrategy;
this.processorThreadNamePrefix = processorThreadNamePrefix;
this.initialLocalState = initialLocalState;
this.queue = new ArrayBlockingQueue<>( maxQueueSize );
processors( initialProcessorCount );
}
@Override
public int processors( int delta )
{
if ( shutDown || delta == 0 )
{
return processors.length;
}
synchronized ( this )
{
if ( shutDown )
{
return processors.length;
}
int requestedNumber = processors.length + delta;
if ( delta > 0 )
{
requestedNumber = min( requestedNumber, maxProcessorCount );
if ( requestedNumber > processors.length )
{
Processor[] newProcessors = Arrays.copyOf( processors, requestedNumber );
for ( int i = processors.length; i < requestedNumber; i++ )
{
newProcessors[i] = new Processor( processorThreadNamePrefix + "-" + i );
}
this.processors = newProcessors;
}
}
else
{
requestedNumber = max( 1, requestedNumber );
if ( requestedNumber < processors.length )
{
Processor[] newProcessors = Arrays.copyOf( processors, requestedNumber );
for ( int i = newProcessors.length; i < processors.length; i++ )
{
processors[i].processorShutDown = true;
}
this.processors = newProcessors;
}
}
return processors.length;
}
}
@Override
public void submit( Task<LOCAL> task )
{
assertHealthy();
try
{
while ( !queue.offer( task, 10, MILLISECONDS ) )
{ // Then just stay here and try
assertHealthy();
}
notifyProcessors();
}
catch ( InterruptedException e )
{
Thread.currentThread().interrupt();
}
}
@Override
public void assertHealthy()
{
if ( shutDown )
{
if ( panic != null )
{
throw new TaskExecutionPanicException( "Executor has been shut down in panic", panic );
}
if ( abortQueued )
{
throw new TaskExecutionPanicException( "Executor has been shut down, aborting queued" );
}
}
}
private void notifyProcessors()
{
for ( Processor processor : processors )
{
parkStrategy.unpark( processor );
}
}
@Override
public synchronized void shutdown( int flags )
{
if ( shutDown )
{
return;
}
boolean awaitAllCompleted = (flags & TaskExecutor.SF_AWAIT_ALL_COMPLETED) != 0;
while ( awaitAllCompleted && !queue.isEmpty() && panic == null /*all bets are off in the event of panic*/ )
{
parkAWhile();
}
this.shutDown = true;
this.abortQueued = (flags & TaskExecutor.SF_ABORT_QUEUED) != 0;
while ( awaitAllCompleted && anyAlive() && panic == null /*all bets are off in the event of panic*/ )
{
parkAWhile();
}
}
@Override
public boolean isShutdown()
{
return shutDown;
}
private boolean anyAlive()
{
for ( Processor processor : processors )
{
if ( processor.isAlive() )
{
return true;
}
}
return false;
}
private void parkAWhile()
{
parkStrategy.park( Thread.currentThread() );
}
private static final UncaughtExceptionHandler SILENT_UNCAUGHT_EXCEPTION_HANDLER = new UncaughtExceptionHandler()
{
@Override
public void uncaughtException( Thread t, Throwable e )
{ // Don't print about it
}
};
private class Processor extends Thread
{
// In addition to the global shutDown flag in the executor each processor has a local flag
// so that an individual processor can be shut down, for example when reducing number of processors
private volatile boolean processorShutDown;
Processor( String name )
{
super( name );
setUncaughtExceptionHandler( SILENT_UNCAUGHT_EXCEPTION_HANDLER );
start();
}
@Override
public void run()
{
// Initialized here since it's the thread itself that needs to call it
final LOCAL threadLocalState = initialLocalState.get();
while ( !shutDown && !processorShutDown )
{
Task<LOCAL> task = queue.poll();
if ( task != null )
{
try
{
task.run( threadLocalState );
}
catch ( Throwable e )
{
panic = e;
shutdown( TaskExecutor.SF_ABORT_QUEUED );
throw launderedException( e );
}
}
else
{
if ( processorShutDown )
{
break;
}
parkAWhile();
}
}
}
}
}