-
Notifications
You must be signed in to change notification settings - Fork 22
/
queue.go
776 lines (639 loc) · 16.7 KB
/
queue.go
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
package fpgo
import (
"errors"
"sync"
"time"
)
// Queue Queue inspired by Collection utils
type Queue[T any] interface {
Put(val T) error
Take() (T, error)
Offer(val T) error
Poll() (T, error)
}
// Stack Stack inspired by Collection utils
type Stack[T any] interface {
Push(val T) error
Pop() (T, error)
}
var (
// ErrQueueIsEmpty Queue Is Empty
ErrQueueIsEmpty = errors.New("queue is empty")
// ErrQueueIsFull Queue Is Full
ErrQueueIsFull = errors.New("queue is full")
// ErrQueueIsClosed Queue Is Closed
ErrQueueIsClosed = errors.New("queue is closed")
// ErrQueueTakeTimeout Queue Take Timeout
ErrQueueTakeTimeout = errors.New("queue take timeout")
// ErrQueuePutTimeout Queue Put Timeout
ErrQueuePutTimeout = errors.New("queue put timeout")
// ErrStackIsEmpty Stack Is Empty
ErrStackIsEmpty = errors.New("stack is empty")
// ErrStackIsFull Stack Is Full
ErrStackIsFull = errors.New("stack is full")
)
// ConcurrentQueue & ConcurrentStack
// ConcurrentQueue ConcurrentQueue inspired by Collection utils
type ConcurrentQueue[T any] struct {
lock sync.RWMutex
queue Queue[T]
}
// NewConcurrentQueue New ConcurrentQueue instance from a Queue[T]
func NewConcurrentQueue[T any](queue Queue[T]) *ConcurrentQueue[T] {
return &ConcurrentQueue[T]{
queue: queue,
}
}
// Put Put the T val(probably blocking)
func (q *ConcurrentQueue[T]) Put(val T) error {
q.lock.Lock()
defer q.lock.Unlock()
return q.queue.Put(val)
}
// Take Take the T val(probably blocking)
func (q *ConcurrentQueue[T]) Take() (T, error) {
q.lock.RLock()
defer q.lock.RUnlock()
return q.queue.Take()
}
// Offer Offer the T val(non-blocking)
func (q *ConcurrentQueue[T]) Offer(val T) error {
q.lock.Lock()
defer q.lock.Unlock()
return q.queue.Offer(val)
}
// Poll Poll the T val(non-blocking)
func (q *ConcurrentQueue[T]) Poll() (T, error) {
q.lock.RLock()
defer q.lock.RUnlock()
return q.queue.Poll()
}
// ConcurrentStack
// ConcurrentStack ConcurrentStack inspired by Collection utils
type ConcurrentStack[T any] struct {
lock sync.RWMutex
stack Stack[T]
}
// NewConcurrentStack New ConcurrentStack instance from a Stack[T]
func NewConcurrentStack[T any](stack Stack[T]) *ConcurrentStack[T] {
return &ConcurrentStack[T]{
stack: stack,
}
}
// Put Put the T val(probably blocking)
func (q *ConcurrentStack[T]) Push(val T) error {
q.lock.Lock()
defer q.lock.Unlock()
return q.stack.Push(val)
}
// Take Take the T val(probably blocking)
func (q *ConcurrentStack[T]) Pop() (T, error) {
q.lock.RLock()
defer q.lock.RUnlock()
return q.stack.Pop()
}
// ChannelQueue
// ChannelQueue ChannelQueue inspired by Collection utils
type ChannelQueue[T any] chan T
// NewChannelQueue New ChannelQueue instance with capacity
func NewChannelQueue[T any](capacity int) ChannelQueue[T] {
return make(ChannelQueue[T], capacity)
}
// Put Put the T val(blocking)
func (q ChannelQueue[T]) Put(val T) error {
q <- val
return nil
}
// PutWithTimeout Put the T val(blocking), with timeout
func (q ChannelQueue[T]) PutWithTimeout(val T, timeout time.Duration) error {
select {
case q <- val:
return nil
case <-time.After(timeout):
return ErrQueuePutTimeout
}
}
// Take Take the T val(blocking)
func (q ChannelQueue[T]) Take() (T, error) {
val, ok := <-q
if !ok {
return *new(T), ErrQueueIsClosed
}
return val, nil
}
// TakeWithTimeout Take the T val(blocking), with timeout
func (q ChannelQueue[T]) TakeWithTimeout(timeout time.Duration) (T, error) {
select {
case val, ok := <-q:
if !ok {
return *new(T), ErrQueueIsClosed
}
return val, nil
case <-time.After(timeout):
return *new(T), ErrQueueTakeTimeout
}
}
// Offer Offer the T val(non-blocking)
func (q ChannelQueue[T]) Offer(val T) error {
select {
case q <- val:
return nil
default:
return ErrQueueIsFull
}
}
// Poll Poll the T val(non-blocking)
func (q ChannelQueue[T]) Poll() (T, error) {
select {
case val := <-q:
return val, nil
default:
return *new(T), ErrQueueIsEmpty
}
}
// LinkedList & DoublyLinkedList
// LinkedListItem LinkedListItem inspired by Collection utils
type LinkedListItem[T any] struct {
Next *LinkedListItem[T]
Val *T
}
// Count Count items
func (listItem *LinkedListItem[T]) Count() int {
count := 1
first := listItem
for first.Next != nil {
count++
first = first.Next
}
return count
}
// Last Get the Last one
func (listItem *LinkedListItem[T]) Last() *LinkedListItem[T] {
last := listItem
for last.Next != nil {
last = last.Next
}
return last
}
// AddLast Add the input item to the last
func (listItem *LinkedListItem[T]) AddLast(input *LinkedListItem[T]) *LinkedListItem[T] {
last := listItem.Last()
last.Next = input
return last
}
// DoublyListItem DoublyListItem inspired by Collection utils
type DoublyListItem[T any] struct {
Next *DoublyListItem[T]
Prev *DoublyListItem[T]
Val *T
}
// Count Count items
func (listItem *DoublyListItem[T]) Count() int {
count := 1
first := listItem.First()
for first.Next != nil {
count++
first = first.Next
}
return count
}
// Last Get the Last one
func (listItem *DoublyListItem[T]) Last() *DoublyListItem[T] {
last := listItem
for last.Next != nil {
last = last.Next
}
return last
}
// First Get the First one
func (listItem *DoublyListItem[T]) First() *DoublyListItem[T] {
first := listItem
for first.Prev != nil {
first = first.Prev
}
return first
}
// AddLast Add the input item to the last
func (listItem *DoublyListItem[T]) AddLast(input *DoublyListItem[T]) *DoublyListItem[T] {
last := listItem.Last()
first := input.First()
last.Next = first
first.Prev = last
return last
}
// AddFirst Add the input item to the first position
func (listItem *DoublyListItem[T]) AddFirst(input *DoublyListItem[T]) *DoublyListItem[T] {
last := input.Last()
first := listItem.First()
last.Next = first
first.Prev = last
return first
}
// LinkedListQueue LinkedListQueue inspired by Collection utils
type LinkedListQueue[T any] struct {
first *DoublyListItem[T]
last *DoublyListItem[T]
count int
nodeGCPool sync.Pool
nodePoolFirst *DoublyListItem[T]
nodeCount int
}
// NewLinkedListQueue New LinkedListQueue instance
func NewLinkedListQueue[T any]() *LinkedListQueue[T] {
newOne := new(LinkedListQueue[T])
newOne.nodeGCPool.New = func() interface{} {
return new(DoublyListItem[T])
}
return newOne
}
func (q *LinkedListQueue[T]) putAllIntoPool(first *DoublyListItem[T]) {
for first != nil {
node := first
first = first.Next
node.Val = nil
node.Prev = nil
node.Next = nil
q.nodeGCPool.Put(node)
}
}
// Count Count Items
func (q *LinkedListQueue[T]) Count() int {
return q.count
}
// ClearNodePool Clear cached LinkedListItem nodes in nodePool
func (q *LinkedListQueue[T]) ClearNodePool() {
q.putAllIntoPool(q.nodePoolFirst)
q.nodeCount = 0
q.nodePoolFirst = nil
}
// KeepNodePoolCount Decrease/Increase LinkedListItem nodes to n items
func (q *LinkedListQueue[T]) KeepNodePoolCount(n int) {
if n <= 0 {
q.ClearNodePool()
return
}
q.nodeCount = n
n--
last := q.nodePoolFirst
if last == nil {
last = q.nodeGCPool.Get().(*DoublyListItem[T])
q.nodePoolFirst = last
}
for n > 0 {
n--
if last.Next == nil {
last.Next = q.nodeGCPool.Get().(*DoublyListItem[T])
}
last = last.Next
}
q.putAllIntoPool(last.Next)
last.Next = nil
}
// CLear Clear all data
func (q *LinkedListQueue[T]) Clear() {
q.nodePoolFirst = q.first
q.nodeCount = q.count
node := q.nodePoolFirst
for node != nil {
node.Val = nil
node.Prev = nil
node = node.Next
}
q.first = nil
q.last = nil
q.count = 0
}
// Put Put the T val to the last position(no-blocking)
func (q *LinkedListQueue[T]) Put(val T) error {
return q.Offer(val)
}
// Take Take the T val from the first position(no-blocking)
func (q *LinkedListQueue[T]) Take() (T, error) {
return q.Poll()
}
// Offer Offer the T val to the last position(non-blocking)
func (q *LinkedListQueue[T]) Offer(val T) error {
// Try get from pool or new one
node := q.generateNode()
node.Val = &val
q.count++
if q.first == nil {
q.first = node
}
last := q.last
if last != nil {
last.Next = node
node.Prev = last
}
q.last = node
return nil
}
// Poll Poll the T val from the first position(non-blocking)
func (q *LinkedListQueue[T]) Poll() (T, error) {
return q.Shift()
}
// Peek Peek the T val from the first position without removing it (non-blocking)
func (q *LinkedListQueue[T]) Peek() (T, error) {
node := q.first
if node == nil {
return *new(T), ErrQueueIsEmpty
}
return *node.Val, nil
}
// Shift Shift the T val from the first position (non-blocking)
func (q *LinkedListQueue[T]) Shift() (T, error) {
node := q.first
if node == nil {
return *new(T), ErrQueueIsEmpty
}
// Remove the first item
q.count--
q.first = node.Next
if q.first == nil {
q.last = nil
}
val := *node.Val
q.recycleNode(node)
return val, nil
}
// Unshift Unshift the T val to the first position(non-blocking)
func (q *LinkedListQueue[T]) Unshift(val T) error {
// Try get from pool or new one
node := q.generateNode()
node.Val = &val
q.count++
if q.last == nil {
q.last = node
}
first := q.first
q.first = node
node.Next = first
if first != nil {
first.Prev = node
}
return nil
}
// Pop Pop the data from the last position(non-blocking)
func (q *LinkedListQueue[T]) Pop() (T, error) {
node := q.last
if node == nil {
return *new(T), ErrStackIsEmpty
}
// Remove the last item
q.count--
q.last = node.Prev
if q.last == nil {
q.first = nil
}
val := *node.Val
q.recycleNode(node)
return val, nil
}
// Push Push the data to the last position(non-blocking)
func (q *LinkedListQueue[T]) Push(val T) error {
// return q.Unshift(val)
return q.Offer(val)
}
func (q *LinkedListQueue[T]) generateNode() *DoublyListItem[T] {
node := q.nodePoolFirst
if node == nil {
node = q.nodeGCPool.Get().(*DoublyListItem[T])
} else {
q.nodeCount--
q.nodePoolFirst = node.Next
node.Next = nil
node.Prev = nil
}
return node
}
func (q *LinkedListQueue[T]) recycleNode(node *DoublyListItem[T]) {
if node == nil {
return
}
// Recycle
q.nodeCount++
node.Val = nil
node.Next = q.nodePoolFirst
node.Prev = nil
q.nodePoolFirst = node
}
// BufferedChannelQueue BlockingQueue with ChannelQueue & scalable pool, inspired by Collection utils
type BufferedChannelQueue[T any] struct {
lock sync.RWMutex
isClosed AtomBool
loadWorkerCh ChannelQueue[int]
freeNodeWorkerCh ChannelQueue[int]
loadFromPoolDuration time.Duration
freeNodeHookPoolIntervalDuration time.Duration
nodeHookPoolSize int
bufferSizeMaximum int
blockingQueue ChannelQueue[T]
pool *LinkedListQueue[T]
}
// NewBufferedChannelQueue New BufferedChannelQueue instance from a Queue[T]
func NewBufferedChannelQueue[T any](channelCapacity int, bufferSizeMaximum int, nodeHookPoolSize int) *BufferedChannelQueue[T] {
pool := NewLinkedListQueue[T]()
newOne := &BufferedChannelQueue[T]{
loadWorkerCh: NewChannelQueue[int](1),
freeNodeWorkerCh: NewChannelQueue[int](1),
blockingQueue: NewChannelQueue[T](channelCapacity),
pool: pool,
loadFromPoolDuration: 10 * time.Millisecond,
freeNodeHookPoolIntervalDuration: 10 * time.Millisecond,
nodeHookPoolSize: nodeHookPoolSize,
bufferSizeMaximum: bufferSizeMaximum,
}
go newOne.freeNodePool()
go newOne.loadFromPool()
return newOne
}
func (q *BufferedChannelQueue[T]) freeNodePool() {
for range q.freeNodeWorkerCh {
time.Sleep(q.freeNodeHookPoolIntervalDuration)
if q.isClosed.Get() {
break
}
q.lock.Lock()
if q.pool.nodeCount > q.nodeHookPoolSize {
q.pool.KeepNodePoolCount(q.nodeHookPoolSize)
}
q.lock.Unlock()
}
}
func (q *BufferedChannelQueue[T]) loadFromPool() {
for range q.loadWorkerCh {
if q.isClosed.Get() {
break
}
q.lock.Lock()
var val T
var pollErr, offerErr error
for q.pool.Count() > 0 {
// Try poll from the pool
val, pollErr = q.pool.Poll()
if pollErr != nil {
break
}
offerErr = q.blockingQueue.Offer(val)
// If failed, unshift it back
if offerErr != nil {
q.pool.Unshift(val)
break
}
}
q.lock.Unlock()
time.Sleep(q.loadFromPoolDuration)
}
}
func (q *BufferedChannelQueue[T]) notifyWorkers() {
q.loadWorkerCh.Offer(1)
q.freeNodeWorkerCh.Offer(1)
}
// SetBufferSizeMaximum Set MaximumBufferSize(maximum number of buffered items outside the ChannelQueue)
func (q *BufferedChannelQueue[T]) SetBufferSizeMaximum(size int) *BufferedChannelQueue[T] {
q.bufferSizeMaximum = size
return q
}
// SetNodeHookPoolSize Set nodeHookPoolSize(the buffering node hooks ideal size)
func (q *BufferedChannelQueue[T]) SetNodeHookPoolSize(size int) *BufferedChannelQueue[T] {
q.nodeHookPoolSize = size
return q
}
// SetLoadFromPoolDuration Set loadFromPoolDuration(the interval to take buffered items into the ChannelQueue)
func (q *BufferedChannelQueue[T]) SetLoadFromPoolDuration(duration time.Duration) *BufferedChannelQueue[T] {
q.loadFromPoolDuration = duration
return q
}
// SetFreeNodeHookPoolIntervalDuration Set freeNodeHookPoolIntervalDuration(the interval to clear buffering node hooks down to nodeHookPoolSize)
func (q *BufferedChannelQueue[T]) SetFreeNodeHookPoolIntervalDuration(duration time.Duration) *BufferedChannelQueue[T] {
q.freeNodeHookPoolIntervalDuration = duration
return q
}
// GetBufferSizeMaximum Get MaximumBufferSize(maximum number of buffered items outside the ChannelQueue)
func (q *BufferedChannelQueue[T]) GetBufferSizeMaximum() int {
return q.bufferSizeMaximum
}
// GetNodeHookPoolSize Get nodeHookPoolSize(the buffering node hooks ideal size)
func (q *BufferedChannelQueue[T]) GetNodeHookPoolSize() int {
return q.nodeHookPoolSize
}
// GetLoadFromPoolDuration Get loadFromPoolDuration(the interval to take buffered items into the ChannelQueue)
func (q *BufferedChannelQueue[T]) GetLoadFromPoolDuration() time.Duration {
return q.loadFromPoolDuration
}
// GetFreeNodeHookPoolIntervalDuration Get freeNodeHookPoolIntervalDuration(the interval to clear buffering node hooks down to nodeHookPoolSize)
func (q *BufferedChannelQueue[T]) GetFreeNodeHookPoolIntervalDuration() time.Duration {
return q.freeNodeHookPoolIntervalDuration
}
// GetChannel Get Channel(for Selecting channels usages)
func (q *BufferedChannelQueue[T]) GetChannel() chan T {
q.notifyWorkers()
return q.blockingQueue
}
// Count Count items
func (q *BufferedChannelQueue[T]) Count() int {
if q.isClosed.Get() {
return 0
}
q.lock.RLock()
defer q.lock.RUnlock()
return len(q.blockingQueue) + q.pool.Count()
}
// IsClosed Is the BufferedChannelQueue closed
func (q *BufferedChannelQueue[T]) IsClosed() bool {
return q.isClosed.Get()
}
// Close Close the BufferedChannelQueue
func (q *BufferedChannelQueue[T]) Close() {
q.lock.Lock()
defer q.lock.Unlock()
q.isClosed.Set(true)
close(q.loadWorkerCh)
close(q.blockingQueue)
}
// Put Put the T val(non-blocking)
func (q *BufferedChannelQueue[T]) Put(val T) error {
// q.lock.Lock()
// defer q.lock.Unlock()
//
// if q.isClosed.Get() {
// return ErrQueueIsClosed
// }
//
// q.lock.Lock()
// poolCount := q.pool.Count()
//
// // If appearing nothing in the pool
// if poolCount == 0 {
// defer q.lock.Unlock()
// // Try channel
// return q.blockingQueue.Put(val)
// }
// q.lock.Unlock()
return q.Offer(val)
}
// // PutWithTimeout Put the T val(blocking), with timeout
// func (q BufferedChannelQueue[T]) PutWithTimeout(val T, timeout time.Duration) error {
// // q.lock.Lock()
// // defer q.lock.Unlock()
//
// if q.isClosed.Get() {
// return ErrQueueIsClosed
// }
//
// return q.blockingQueue.PutWithTimeout(val, timeout)
// }
// Take Take the T val(blocking)
func (q *BufferedChannelQueue[T]) Take() (T, error) {
if q.isClosed.Get() {
return *new(T), ErrQueueIsClosed
}
q.notifyWorkers()
return q.blockingQueue.Take()
}
// TakeWithTimeout Take the T val(blocking), with timeout
func (q *BufferedChannelQueue[T]) TakeWithTimeout(timeout time.Duration) (T, error) {
if q.isClosed.Get() {
return *new(T), ErrQueueIsClosed
}
q.notifyWorkers()
return q.blockingQueue.TakeWithTimeout(timeout)
}
// Offer Offer the T val(non-blocking)
func (q *BufferedChannelQueue[T]) Offer(val T) error {
q.lock.Lock()
defer q.lock.Unlock()
if q.isClosed.Get() {
return ErrQueueIsClosed
}
poolCount := q.pool.Count()
// If appearing nothing in the pool
if poolCount == 0 {
// Try channel
err := q.blockingQueue.Offer(val)
if err == nil {
// Success
return nil
} else if err == ErrQueueIsFull {
// Do nothing and let pool.Offer(val)
} else {
// Other
return err
}
}
// Before +1: >=, After +1: >
if poolCount >= q.bufferSizeMaximum {
return ErrQueueIsFull
}
q.pool.Offer(val)
q.loadWorkerCh.Offer(1)
return nil
}
// Poll Poll the T val(non-blocking)
func (q *BufferedChannelQueue[T]) Poll() (T, error) {
if q.isClosed.Get() {
return *new(T), ErrQueueIsClosed
}
q.notifyWorkers()
return q.blockingQueue.Poll()
}