/
MpscArrayQueue.java
executable file
·621 lines (555 loc) · 18.5 KB
/
MpscArrayQueue.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
* Licensed 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.
*/
package org.jctools.queues;
import org.jctools.util.PortableJvmInfo;
import static org.jctools.util.UnsafeAccess.UNSAFE;
import static org.jctools.util.UnsafeAccess.fieldOffset;
import static org.jctools.util.UnsafeRefArrayAccess.*;
import java.util.Iterator;
abstract class MpscArrayQueueL1Pad<E> extends ConcurrentCircularArrayQueue<E>
{
long p00, p01, p02, p03, p04, p05, p06, p07;
long p10, p11, p12, p13, p14, p15, p16;
MpscArrayQueueL1Pad(int capacity)
{
super(capacity);
}
}
//$gen:ordered-fields
abstract class MpscArrayQueueProducerIndexField<E> extends MpscArrayQueueL1Pad<E>
{
private final static long P_INDEX_OFFSET = fieldOffset(MpscArrayQueueProducerIndexField.class, "producerIndex");
private volatile long producerIndex;
MpscArrayQueueProducerIndexField(int capacity)
{
super(capacity);
}
@Override
public final long lvProducerIndex()
{
return producerIndex;
}
final boolean casProducerIndex(long expect, long newValue)
{
return UNSAFE.compareAndSwapLong(this, P_INDEX_OFFSET, expect, newValue);
}
}
abstract class MpscArrayQueueMidPad<E> extends MpscArrayQueueProducerIndexField<E>
{
long p01, p02, p03, p04, p05, p06, p07;
long p10, p11, p12, p13, p14, p15, p16, p17;
MpscArrayQueueMidPad(int capacity)
{
super(capacity);
}
}
//$gen:ordered-fields
abstract class MpscArrayQueueProducerLimitField<E> extends MpscArrayQueueMidPad<E>
{
private final static long P_LIMIT_OFFSET = fieldOffset(MpscArrayQueueProducerLimitField.class, "producerLimit");
// First unavailable index the producer may claim up to before rereading the consumer index
private volatile long producerLimit;
MpscArrayQueueProducerLimitField(int capacity)
{
super(capacity);
this.producerLimit = capacity;
}
final long lvProducerLimit()
{
return producerLimit;
}
final void soProducerLimit(long newValue)
{
UNSAFE.putOrderedLong(this, P_LIMIT_OFFSET, newValue);
}
}
abstract class MpscArrayQueueL2Pad<E> extends MpscArrayQueueProducerLimitField<E>
{
long p00, p01, p02, p03, p04, p05, p06, p07;
long p10, p11, p12, p13, p14, p15, p16;
MpscArrayQueueL2Pad(int capacity)
{
super(capacity);
}
}
//$gen:ordered-fields
abstract class MpscArrayQueueConsumerIndexField<E> extends MpscArrayQueueL2Pad<E>
{
private final static long C_INDEX_OFFSET = fieldOffset(MpscArrayQueueConsumerIndexField.class, "consumerIndex");
private volatile long consumerIndex;
MpscArrayQueueConsumerIndexField(int capacity)
{
super(capacity);
}
@Override
public final long lvConsumerIndex()
{
return consumerIndex;
}
final long lpConsumerIndex()
{
return UNSAFE.getLong(this, C_INDEX_OFFSET);
}
final void soConsumerIndex(long newValue)
{
UNSAFE.putOrderedLong(this, C_INDEX_OFFSET, newValue);
}
}
abstract class MpscArrayQueueL3Pad<E> extends MpscArrayQueueConsumerIndexField<E>
{
long p01, p02, p03, p04, p05, p06, p07;
long p10, p11, p12, p13, p14, p15, p16, p17;
MpscArrayQueueL3Pad(int capacity)
{
super(capacity);
}
}
/**
* A Multi-Producer-Single-Consumer queue based on a {@link org.jctools.queues.ConcurrentCircularArrayQueue}. This
* implies that any thread may call the offer method, but only a single thread may call poll/peek for correctness to
* maintained. <br>
* This implementation follows patterns documented on the package level for False Sharing protection.<br>
* This implementation is using the <a href="http://sourceforge.net/projects/mc-fastflow/">Fast Flow</a>
* method for polling from the queue (with minor change to correctly publish the index) and an extension of
* the Leslie Lamport concurrent queue algorithm (originated by Martin Thompson) on the producer side.<br>
*
* @param <E>
* @author nitsanw
*/
public class MpscArrayQueue<E> extends MpscArrayQueueL3Pad<E>
{
public MpscArrayQueue(final int capacity)
{
super(capacity);
}
/**
* {@link #offer}} if {@link #size()} is less than threshold.
*
* @param e the object to offer onto the queue, not null
* @param threshold the maximum allowable size
* @return true if the offer is successful, false if queue size exceeds threshold
* @since 1.0.1
*/
public boolean offerIfBelowThreshold(final E e, int threshold)
{
if (null == e)
{
throw new NullPointerException();
}
final long mask = this.mask;
final long capacity = mask + 1;
long producerLimit = lvProducerLimit(); // LoadLoad
long pIndex;
do
{
pIndex = lvProducerIndex(); // LoadLoad
long available = producerLimit - pIndex;
long size = capacity - available;
if (size >= threshold)
{
final long cIndex = lvConsumerIndex(); // LoadLoad
size = pIndex - cIndex;
if (size >= threshold)
{
return false; // the size exceeds threshold
}
else
{
// update producer limit to the next index that we must recheck the consumer index
producerLimit = cIndex + capacity;
// this is racy, but the race is benign
soProducerLimit(producerLimit);
}
}
}
while (!casProducerIndex(pIndex, pIndex + 1));
/*
* NOTE: the new producer index value is made visible BEFORE the element in the array. If we relied on
* the index visibility to poll() we would need to handle the case where the element is not visible.
*/
// Won CAS, move on to storing
final long offset = calcElementOffset(pIndex, mask);
soElement(buffer, offset, e); // StoreStore
return true; // AWESOME :)
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Lock free offer using a single CAS. As class name suggests access is permitted to many threads
* concurrently.
*
* @see java.util.Queue#offer
* @see org.jctools.queues.MessagePassingQueue#offer
*/
@Override
public boolean offer(final E e)
{
if (null == e)
{
throw new NullPointerException();
}
// use a cached view on consumer index (potentially updated in loop)
final long mask = this.mask;
long producerLimit = lvProducerLimit(); // LoadLoad
long pIndex;
do
{
pIndex = lvProducerIndex(); // LoadLoad
if (pIndex >= producerLimit)
{
final long cIndex = lvConsumerIndex(); // LoadLoad
producerLimit = cIndex + mask + 1;
if (pIndex >= producerLimit)
{
return false; // FULL :(
}
else
{
// update producer limit to the next index that we must recheck the consumer index
// this is racy, but the race is benign
soProducerLimit(producerLimit);
}
}
}
while (!casProducerIndex(pIndex, pIndex + 1));
/*
* NOTE: the new producer index value is made visible BEFORE the element in the array. If we relied on
* the index visibility to poll() we would need to handle the case where the element is not visible.
*/
// Won CAS, move on to storing
final long offset = calcElementOffset(pIndex, mask);
soElement(buffer, offset, e); // StoreStore
return true; // AWESOME :)
}
/**
* A wait free alternative to offer which fails on CAS failure.
*
* @param e new element, not null
* @return 1 if next element cannot be filled, -1 if CAS failed, 0 if successful
*/
public final int failFastOffer(final E e)
{
if (null == e)
{
throw new NullPointerException();
}
final long mask = this.mask;
final long capacity = mask + 1;
final long pIndex = lvProducerIndex(); // LoadLoad
long producerLimit = lvProducerLimit(); // LoadLoad
if (pIndex >= producerLimit)
{
final long cIndex = lvConsumerIndex(); // LoadLoad
producerLimit = cIndex + capacity;
if (pIndex >= producerLimit)
{
return 1; // FULL :(
}
else
{
// update producer limit to the next index that we must recheck the consumer index
soProducerLimit(producerLimit); // StoreLoad
}
}
// look Ma, no loop!
if (!casProducerIndex(pIndex, pIndex + 1))
{
return -1; // CAS FAIL :(
}
// Won CAS, move on to storing
final long offset = calcElementOffset(pIndex, mask);
soElement(buffer, offset, e);
return 0; // AWESOME :)
}
/**
* {@inheritDoc}
* <p>
* IMPLEMENTATION NOTES:<br>
* Lock free poll using ordered loads/stores. As class name suggests access is limited to a single thread.
*
* @see java.util.Queue#poll
* @see org.jctools.queues.MessagePassingQueue#poll
*/
@Override
public E poll()
{
final long cIndex = lpConsumerIndex();
final long offset = calcElementOffset(cIndex);
// Copy field to avoid re-reading after volatile load
final E[] buffer = this.buffer;
// If we can't see the next available element we can't poll
E e = lvElement(buffer, offset); // LoadLoad
if (null == e)
{
/*
* NOTE: Queue may not actually be empty in the case of a producer (P1) being interrupted after
* winning the CAS on offer but before storing the element in the queue. Other producers may go on
* to fill up the queue after this element.
*/
if (cIndex != lvProducerIndex())
{
do
{
e = lvElement(buffer, offset);
}
while (e == null);
}
else
{
return null;
}
}
spElement(buffer, offset, null);
soConsumerIndex(cIndex + 1); // StoreStore
return e;
}
/**
* {@inheritDoc}
* <p>
* IMPLEMENTATION NOTES:<br>
* Lock free peek using ordered loads. As class name suggests access is limited to a single thread.
*
* @see java.util.Queue#poll
* @see org.jctools.queues.MessagePassingQueue#poll
*/
@Override
public E peek()
{
// Copy field to avoid re-reading after volatile load
final E[] buffer = this.buffer;
final long cIndex = lpConsumerIndex(); // LoadLoad
final long offset = calcElementOffset(cIndex);
E e = lvElement(buffer, offset);
if (null == e)
{
/*
* NOTE: Queue may not actually be empty in the case of a producer (P1) being interrupted after
* winning the CAS on offer but before storing the element in the queue. Other producers may go on
* to fill up the queue after this element.
*/
if (cIndex != lvProducerIndex())
{
do
{
e = lvElement(buffer, offset);
}
while (e == null);
}
else
{
return null;
}
}
return e;
}
@Override
public boolean relaxedOffer(E e)
{
return offer(e);
}
@Override
public E relaxedPoll()
{
final E[] buffer = this.buffer;
final long cIndex = lpConsumerIndex();
final long offset = calcElementOffset(cIndex);
// If we can't see the next available element we can't poll
E e = lvElement(buffer, offset); // LoadLoad
if (null == e)
{
return null;
}
spElement(buffer, offset, null);
soConsumerIndex(cIndex + 1); // StoreStore
return e;
}
@Override
public E relaxedPeek()
{
final E[] buffer = this.buffer;
final long mask = this.mask;
final long cIndex = lpConsumerIndex();
return lvElement(buffer, calcElementOffset(cIndex, mask));
}
@Override
public int drain(Consumer<E> c)
{
return drain(c, capacity());
}
@Override
public int fill(Supplier<E> s)
{
long result = 0;// result is a long because we want to have a safepoint check at regular intervals
final int capacity = capacity();
do
{
final int filled = fill(s, PortableJvmInfo.RECOMENDED_OFFER_BATCH);
if (filled == 0)
{
return (int) result;
}
result += filled;
}
while (result <= capacity);
return (int) result;
}
@Override
public int drain(final Consumer<E> c, final int limit)
{
final E[] buffer = this.buffer;
final long mask = this.mask;
final long cIndex = lpConsumerIndex();
for (int i = 0; i < limit; i++)
{
final long index = cIndex + i;
final long offset = calcElementOffset(index, mask);
final E e = lvElement(buffer, offset);// LoadLoad
if (null == e)
{
return i;
}
spElement(buffer, offset, null);
soConsumerIndex(index + 1); // ordered store -> atomic and ordered for size()
c.accept(e);
}
return limit;
}
@Override
public int fill(Supplier<E> s, int limit)
{
final long mask = this.mask;
final long capacity = mask + 1;
long producerLimit = lvProducerLimit(); // LoadLoad
long pIndex;
int actualLimit = 0;
do
{
pIndex = lvProducerIndex(); // LoadLoad
long available = producerLimit - pIndex;
if (available <= 0)
{
final long cIndex = lvConsumerIndex(); // LoadLoad
producerLimit = cIndex + capacity;
available = producerLimit - pIndex;
if (available <= 0)
{
return 0; // FULL :(
}
else
{
// update producer limit to the next index that we must recheck the consumer index
soProducerLimit(producerLimit); // StoreLoad
}
}
actualLimit = Math.min((int) available, limit);
}
while (!casProducerIndex(pIndex, pIndex + actualLimit));
// right, now we claimed a few slots and can fill them with goodness
final E[] buffer = this.buffer;
for (int i = 0; i < actualLimit; i++)
{
// Won CAS, move on to storing
final long offset = calcElementOffset(pIndex + i, mask);
soElement(buffer, offset, s.get());
}
return actualLimit;
}
@Override
public void drain(Consumer<E> c, WaitStrategy w, ExitCondition exit)
{
final E[] buffer = this.buffer;
final long mask = this.mask;
long cIndex = lpConsumerIndex();
int counter = 0;
while (exit.keepRunning())
{
for (int i = 0; i < 4096; i++)
{
final long offset = calcElementOffset(cIndex, mask);
final E e = lvElement(buffer, offset);// LoadLoad
if (null == e)
{
counter = w.idle(counter);
continue;
}
cIndex++;
counter = 0;
spElement(buffer, offset, null);
soConsumerIndex(cIndex); // ordered store -> atomic and ordered for size()
c.accept(e);
}
}
}
@Override
public void fill(Supplier<E> s, WaitStrategy w, ExitCondition exit)
{
int idleCounter = 0;
while (exit.keepRunning())
{
if (fill(s, PortableJvmInfo.RECOMENDED_OFFER_BATCH) == 0)
{
idleCounter = w.idle(idleCounter);
continue;
}
idleCounter = 0;
}
}
/**
* Get an iterator for this queue. This method is thread safe.
* <p>
* The iterator provides a best-effort snapshot of the elements in the queue.
* The returned iterator is not guaranteed to return elements in queue order,
* and races with the consumer thread may cause gaps in the sequence of returned elements.
* Like {link #relaxedPoll}, the iterator may not immediately return newly inserted elements.
*
* @return The iterator.
*/
@Override
public final Iterator<E> iterator() {
final long cIndex = lvConsumerIndex();
final long pIndex = lvProducerIndex();
return new WeakIterator(cIndex, pIndex);
}
private final class WeakIterator implements Iterator<E> {
private final long pIndex;
private long nextIndex;
private E nextElement;
WeakIterator(long cIndex, long pIndex) {
this.nextIndex = cIndex;
this.pIndex = pIndex;
nextElement = getNext();
}
@Override
public boolean hasNext() {
return nextElement != null;
}
@Override
public E next() {
E e = nextElement;
nextElement = getNext();
return e;
}
private E getNext() {
while (nextIndex < pIndex) {
long offset = calcElementOffset(nextIndex++);
E e = lvElement(buffer, offset);
if (e != null) {
return e;
}
}
return null;
}
}
}