forked from fanliao/go-concurrentMap
/
concurrentmap.go
1172 lines (1053 loc) · 31.6 KB
/
concurrentmap.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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package concurrent
import (
"errors"
//"fmt"
"io"
"math"
"reflect"
"sync"
"sync/atomic"
"unsafe"
)
const (
/**
* The default initial capacity for this table,
* used when not otherwise specified in a constructor.
*/
DEFAULT_INITIAL_CAPACITY int = 16
/**
* The default load factor for this table, used when not
* otherwise specified in a constructor.
*/
DEFAULT_LOAD_FACTOR float32 = 0.75
/**
* The default concurrency level for this table, used when not
* otherwise specified in a constructor.
*/
DEFAULT_CONCURRENCY_LEVEL int = 16
/**
* The maximum capacity, used if a higher value is implicitly
* specified by either of the constructors with arguments. MUST
* be a power of two <= 1<<30 to ensure that entries are indexable
* using ints.
*/
MAXIMUM_CAPACITY int = 1 << 30
/**
* The maximum number of segments to allow; used to bound
* constructor arguments.
*/
MAX_SEGMENTS int = 1 << 16 // slightly conservative
/**
* Number of unsynchronized retries in size and containsValue
* methods before resorting to locking. This is used to avoid
* unbounded retries if tables undergo continuous modification
* which would make it impossible to obtain an accurate result.
*/
RETRIES_BEFORE_LOCK int = 2
)
var (
Debug = false
NilKeyError = errors.New("Do not support nil as key")
NilValueError = errors.New("Do not support nil as value")
NilActionError = errors.New("Do not support nil as action")
NonSupportKey = errors.New("Non support for pointer, interface, channel, slice, map and function ")
IllegalArgError = errors.New("IllegalArgumentException")
)
type Hashable interface {
HashBytes() []byte
Equals(v2 interface{}) bool
}
type hashEnginer struct {
putFunc func(w io.Writer, v interface{})
}
//segments is read-only, don't need synchronized
type ConcurrentMap struct {
engChecker *Once
eng unsafe.Pointer
/**
* Kind of Reflect value for key
*/
kind unsafe.Pointer
/**
* Mask value for indexing into segments. The upper bits of a
* key's hash code are used to choose the segment.
*/
segmentMask int
/**
* Shift value for indexing within segments.
*/
segmentShift uint
/**
* The segments, each of which is a specialized hash table
*/
segments []*Segment
}
/**
* Returns the segment that should be used for key with given hash
* @param hash the hash code for the key
* @return the segment
*/
func (this *ConcurrentMap) segmentFor(hash uint32) *Segment {
//默认segmentShift是28,segmentMask是(0xFFFFFFF),hash>>this.segmentShift就是取前面4位
//&segmentMask似乎没有必要
//get first four bytes
return this.segments[(hash>>this.segmentShift)&uint32(this.segmentMask)]
}
/**
* Returns true if this map contains no key-value mappings.
*/
func (this *ConcurrentMap) IsEmpty() bool {
segments := this.segments
/*
* if any segment count isn't zero, Map will be no empty.
* 检查是否每个segment的count是否为0,并记录modCount和总和
*/
mc := make([]int32, len(segments))
var mcsum int32 = 0
for i := 0; i < len(segments); i++ {
if atomic.LoadInt32(&segments[i].count) != 0 {
return false
} else {
mc[i] = atomic.LoadInt32(&segments[i].modCount)
mcsum += mc[i]
}
}
/*
* if mcsum isn't zero, then modification is made,
* we will check per-segments count and if modCount be modified
* to avoid ABA problems in which an element in one segment was added and
* in another removed during traversal
*/
if mcsum != 0 {
for i := 0; i < len(segments); i++ {
if atomic.LoadInt32(&segments[i].count) != 0 || mc[i] != atomic.LoadInt32(&segments[i].modCount) {
return false
}
}
}
return true
}
/**
* Returns the number of key-value mappings in this map.
*/
func (this *ConcurrentMap) Size() int32 {
segments := this.segments
var sum int32 = 0
var check int32 = 0
mc := make([]int32, len(segments))
// Try a few times to get accurate count. On failure due to
// continuous async changes in table, resort to locking.
for k := 0; k < RETRIES_BEFORE_LOCK; k++ {
check = 0
sum = 0
var mcsum int32 = 0
for i := 0; i < len(segments); i++ {
sum += atomic.LoadInt32(&segments[i].count)
mc[i] = atomic.LoadInt32(&segments[i].modCount)
mcsum += mc[i]
}
if mcsum != 0 {
for i := 0; i < len(segments); i++ {
check += atomic.LoadInt32(&segments[i].count)
if mc[i] != atomic.LoadInt32(&segments[i].modCount) {
//async change happens, force retry
check = -1 //
break
}
}
}
//twoice counts ar same, it means no async change,
//then will return sum
if check == sum {
break
}
}
//async change happens in each loop
//lock all segments to get accurate count
if check != sum {
sum = 0
for i := 0; i < len(segments); i++ {
segments[i].lock.Lock()
}
for i := 0; i < len(segments); i++ {
sum += segments[i].count
}
for i := 0; i < len(segments); i++ {
segments[i].lock.Unlock()
}
}
return sum
}
/**
* Returns the value to which the specified key is mapped,
* or nil if this map contains no mapping for the key.
*/
func (this *ConcurrentMap) Get(key interface{}) (value interface{}, err error) {
if isNil(key) {
return nil, NilKeyError
}
//if atomic.LoadPointer(&this.kind) == nil {
// return nil, nil
//}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("Get, %v, %v\n", key, hash)
value = this.segmentFor(hash).get(key, hash)
}
return
}
/**
* Tests if the specified object is a key in this table.
*
* @param key possible key
* @return true if and only if the specified object is a key in this table,
* as determined by the == method; false otherwise.
*/
func (this *ConcurrentMap) ContainsKey(key interface{}) (found bool, err error) {
if isNil(key) {
return false, NilKeyError
}
if atomic.LoadPointer(&this.kind) == nil {
return false, nil
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("ContainsKey, %v, %v\n", key, hash)
found = this.segmentFor(hash).containsKey(key, hash)
}
//hash := hash2(hashKey(key, this, false))
//Printf("ContainsKey, %v, %v\n", key, hash)
//found = this.segmentFor(hash).containsKey(key, hash)
return
}
/**
* Maps the specified key to the specified value in this table.
* Neither the key nor the value can be nil.
*
* The value can be retrieved by calling the get method
* with a key that is equal to the original key.
*
* @param key with which the specified value is to be associated
* @param value to be associated with the specified key
*
* @return the previous value associated with key, or
* nil if there was no mapping for key
*/
func (this *ConcurrentMap) Put(key interface{}, value interface{}) (oldVal interface{}, err error) {
if isNil(key) {
return nil, NilKeyError
}
if isNil(value) {
return nil, NilValueError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("Put, %v, %v\n", key, hash)
oldVal = this.segmentFor(hash).put(key, hash, value, false, nil)
}
//hash := hash2(hashKey(key, this, true))
//Printf("Put, %v, %v\n", key, hash)
//oldVal = this.segmentFor(hash).put(key, hash, value, false)
return
}
/**
* If mapping exists for the key, then maps the specified key to the specified value in this table.
* else will ignore.
* Neither the key nor the value can be nil.
*
* The value can be retrieved by calling the get method
* with a key that is equal to the original key.
*
* @return the previous value associated with the specified key,
* or nil if there was no mapping for the key
*/
func (this *ConcurrentMap) PutIfAbsent(key interface{}, value interface{}) (oldVal interface{}, err error) {
if isNil(key) {
return nil, NilKeyError
}
if isNil(value) {
return nil, NilValueError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("PutIfAbsent, %v, %v\n", key, hash)
oldVal = this.segmentFor(hash).put(key, hash, value, true, nil)
}
//hash := hash2(hashKey(key, this, true))
//Printf("PutIfAbsent, %v, %v\n", key, hash)
//oldVal = this.segmentFor(hash).put(key, hash, value, true)
return
}
/**
* Maps the specified key to the value that be returned by specified function in this table.
* The key can not be nil.
*
* The value mapping specified key will be passed into action function as parameter.
* If mapping does not exists for the key, nil will be passed into action function.
* If return value by action function is nil, the specified key will be remove from map.
*
* @param key with which the specified value is to be associated
* @param action that be called to generate new value mapping the specified key
*
* @return the previous value associated with key, or
* nil if there was no mapping for key
*/
func (this *ConcurrentMap) Update(key interface{}, action func(oldVal interface{}) (newVal interface{})) (oldVal interface{}, err error) {
if isNil(key) {
return nil, NilKeyError
}
if action == nil {
return nil, NilActionError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("Put, %v, %v\n", key, hash)
oldVal = this.segmentFor(hash).put(key, hash, nil, false, action)
}
//hash := hash2(hashKey(key, this, true))
//Printf("Put, %v, %v\n", key, hash)
//oldVal = this.segmentFor(hash).put(key, hash, value, false)
return
}
/**
* Copies all of the mappings from the specified map to this one.
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified map.
*
* @param m mappings to be stored in this map
*/
func (this *ConcurrentMap) PutAll(m map[interface{}]interface{}) (err error) {
if isNil(m) {
err = errors.New("Cannot copy nil map")
}
for k, v := range m {
this.Put(k, v)
}
return
}
/**
* Removes the key (and its corresponding value) from this map.
* This method does nothing if the key is not in the map.
*
* @param key the key that needs to be removed
* @return the previous value associated with key, or nil if there was no mapping for key
*/
func (this *ConcurrentMap) Remove(key interface{}) (oldVal interface{}, err error) {
if isNil(key) {
return nil, NilKeyError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("Remove, %v, %v\n", key, hash)
oldVal = this.segmentFor(hash).remove(key, hash, nil)
}
//hash := hash2(hashKey(key, this, true))
//Printf("Remove, %v, %v\n", key, hash)
//oldVal = this.segmentFor(hash).remove(key, hash, nil)
return
}
/**
* Removes the mapping for the key and value from this map.
* This method does nothing if no mapping for the key and value.
*
* @return true if mapping be removed, false otherwise
*/
func (this *ConcurrentMap) RemoveEntry(key interface{}, value interface{}) (ok bool, err error) {
if isNil(key) {
return false, NilKeyError
}
if isNil(value) {
return false, NilValueError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("RemoveEntry, %v, %v\n", key, hash)
ok = this.segmentFor(hash).remove(key, hash, value) != nil
}
//hash := hash2(hashKey(key, this, true))
//Printf("RemoveEntry, %v, %v\n", key, hash)
//ok = this.segmentFor(hash).remove(key, hash, value) != nil
return
}
/**
* CompareAndReplace executes the compare-and-replace operation.
* Replaces the value if the mapping exists for the previous and key from this map.
* This method does nothing if no mapping for the key and value.
*
* @return true if value be replaced, false otherwise
*/
func (this *ConcurrentMap) CompareAndReplace(key interface{}, oldVal interface{}, newVal interface{}) (ok bool, err error) {
if isNil(key) {
return false, NilKeyError
}
if isNil(oldVal) || isNil(newVal) {
return false, NilValueError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("CompareAndReplace, %v, %v\n", key, hash)
ok = this.segmentFor(hash).compareAndReplace(key, hash, oldVal, newVal)
}
//hash := hash2(hashKey(key, this, true))
//Printf("CompareAndReplace, %v, %v\n", key, hash)
//ok = this.segmentFor(hash).replaceWithOld(key, hash, oldVal, newVal)
return
}
/**
* Replaces the value if the key is in the map.
* This method does nothing if no mapping for the key.
*
* @return the previous value associated with the specified key,
* or nil if there was no mapping for the key
*/
func (this *ConcurrentMap) Replace(key interface{}, value interface{}) (oldVal interface{}, err error) {
if isNil(key) {
return nil, NilKeyError
}
if isNil(value) {
return nil, NilValueError
}
if hash, e := hashKey(key, this, false); e != nil {
err = e
} else {
Printf("Replace, %v, %v\n", key, hash)
oldVal = this.segmentFor(hash).replace(key, hash, value)
}
//hash := hash2(hashKey(key, this, true))
//Printf("Replace, %v, %v\n", key, hash)
//oldVal = this.segmentFor(hash).replace(key, hash, value)
return
}
/**
* Removes all of the mappings from this map.
*/
func (this *ConcurrentMap) Clear() {
for i := 0; i < len(this.segments); i++ {
this.segments[i].clear()
}
}
//Iterator returns a iterator for ConcurrentMap
func (this *ConcurrentMap) Iterator() *MapIterator {
return newMapIterator(this)
}
//ToSlice returns a slice that includes all key-value Entry in ConcurrentMap
func (this *ConcurrentMap) ToSlice() (kvs []*Entry) {
kvs = make([]*Entry, 0, this.Size())
itr := this.Iterator()
for itr.HasNext() {
kvs = append(kvs, itr.nextEntry())
}
return
}
func (this *ConcurrentMap) parseKey(key interface{}) (err error) {
this.engChecker.Do(func() {
var eng *hashEnginer
val := key
if _, ok := val.(Hashable); ok {
eng = hasherEng
} else {
switch v := val.(type) {
case bool:
_ = v
eng = boolEng
case int:
eng = intEng
case int8:
eng = int8Eng
case int16:
eng = int16Eng
case int32:
eng = int32Eng
case int64:
eng = int64Eng
case uint:
eng = uintEng
case uint8:
eng = uint8Eng
case uint16:
eng = uint16Eng
case uint32:
eng = uint32Eng
case uint64:
eng = uint64Eng
case uintptr:
eng = uintptrEng
case float32:
eng = float32Eng
case float64:
eng = float64Eng
case complex64:
eng = complex64Eng
case complex128:
eng = complex128Eng
case string:
eng = stringEng
default:
Printf("key = %v, other case\n", key)
//some types can be used as key, we can use equals to test
//_ = val == val
rv := reflect.ValueOf(val)
if ki, e := getKeyInfo(rv.Type()); e != nil {
err = e
return
} else {
putF := getPutFunc(ki)
eng = &hashEnginer{}
eng.putFunc = putF
}
}
}
this.eng = unsafe.Pointer(eng)
Printf("key = %v, eng=%v, %v\n", key, this.eng, eng)
})
return
}
func (this *ConcurrentMap) newSegment(initialCapacity int, lf float32) (s *Segment) {
s = new(Segment)
s.loadFactor = lf
table := make([]unsafe.Pointer, initialCapacity)
s.setTable(table)
s.lock = new(sync.Mutex)
s.m = this
return
}
func newConcurrentMap3(initialCapacity int,
loadFactor float32, concurrencyLevel int) (m *ConcurrentMap) {
m = &ConcurrentMap{}
if !(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0 {
panic(IllegalArgError)
}
if concurrencyLevel > MAX_SEGMENTS {
concurrencyLevel = MAX_SEGMENTS
}
// Find power-of-two sizes best matching arguments
sshift := 0
ssize := 1
for ssize < concurrencyLevel {
sshift++
ssize = ssize << 1
}
m.segmentShift = uint(32) - uint(sshift)
m.segmentMask = ssize - 1
m.segments = make([]*Segment, ssize)
if initialCapacity > MAXIMUM_CAPACITY {
initialCapacity = MAXIMUM_CAPACITY
}
c := initialCapacity / ssize
if c*ssize < initialCapacity {
c++
}
cap := 1
for cap < c {
cap <<= 1
}
for i := 0; i < len(m.segments); i++ {
m.segments[i] = m.newSegment(cap, loadFactor)
}
m.engChecker = new(Once)
return
}
/**
* Creates a new, empty map with the specified initial
* capacity, load factor and concurrency level.
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements.
*
* @param loadFactor the load factor threshold, used to control resizing.
* Resizing may be performed when the average number of elements per
* bin exceeds this threshold.
*
* @param concurrencyLevel the estimated number of concurrently
* updating threads. The implementation performs internal sizing
* to try to accommodate this many threads.
*
* panic error "IllegalArgumentException" if the initial capacity is
* negative or the load factor or concurrencyLevel are
* nonpositive.
*
* Creates a new, empty map with a default initial capacity (16),
* load factor (0.75) and concurrencyLevel (16).
*/
func NewConcurrentMap(paras ...interface{}) (m *ConcurrentMap) {
ok := false
cap := DEFAULT_INITIAL_CAPACITY
factor := DEFAULT_LOAD_FACTOR
concurrent_lvl := DEFAULT_CONCURRENCY_LEVEL
if len(paras) >= 1 {
if cap, ok = paras[0].(int); !ok {
panic(IllegalArgError)
}
}
if len(paras) >= 2 {
if factor, ok = paras[1].(float32); !ok {
panic(IllegalArgError)
}
}
if len(paras) >= 3 {
if concurrent_lvl, ok = paras[2].(int); !ok {
panic(IllegalArgError)
}
}
m = newConcurrentMap3(cap, factor, concurrent_lvl)
return
}
/**
* Creates a new map with the same mappings as the given map.
* The map is created with a capacity of 1.5 times the number
* of mappings in the given map or 16 (whichever is greater),
* and a default load factor (0.75) and concurrencyLevel (16).
*
* @param m the map
*/
func NewConcurrentMapFromMap(m map[interface{}]interface{}) *ConcurrentMap {
cm := newConcurrentMap3(int(math.Max(float64(float32(len(m))/DEFAULT_LOAD_FACTOR+1),
float64(DEFAULT_INITIAL_CAPACITY))),
DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL)
cm.PutAll(m)
return cm
}
/**
* ConcurrentHashMap list entry.
* Note only value field is variable and must use atomic to read/write it, other three fields are read-only after initializing.
* so can use unsynchronized reader, the Segment.readValueUnderLock method is used as a
* backup in case a nil (pre-initialized) value is ever seen in
* an unsynchronized access method.
*/
type Entry struct {
key interface{}
hash uint32
value unsafe.Pointer
next *Entry
}
func (this *Entry) Key() interface{} {
return this.key
}
func (this *Entry) Value() interface{} {
return *((*interface{})(atomic.LoadPointer(&this.value)))
}
func (this *Entry) fastValue() interface{} {
return *((*interface{})(this.value))
}
func (this *Entry) storeValue(v *interface{}) {
atomic.StorePointer(&this.value, unsafe.Pointer(v))
}
type Segment struct {
m *ConcurrentMap //point to concurrentMap.eng, so it is **hashEnginer
/**
* The number of elements in this segment's region.
* Must use atomic package's LoadInt32 and StoreInt32 functions to read/write this field
* otherwise read operation may cannot read latest value
*/
count int32
/**
* Number of updates that alter the size of the table. This is
* used during bulk-read methods to make sure they see a
* consistent snapshot: If modCounts change during a traversal
* of segments computing size or checking containsValue, then
* we might have an inconsistent view of state so (usually)
* must retry.
*/
modCount int32
/**
* The table is rehashed when its size exceeds this threshold.
* (The value of this field is always (int)(capacity *
* loadFactor).)
*/
threshold int32
/**
* The per-segment table.
* Use unsafe.Pointer because must use atomic.LoadPointer function in read operations.
*/
pTable unsafe.Pointer //point to []unsafe.Pointer
/**
* The load factor for the hash table. Even though this value
* is same for all segments, it is replicated to avoid needing
* links to outer object.
*/
loadFactor float32
lock *sync.Mutex
}
func (this *Segment) enginer() *hashEnginer {
return (*hashEnginer)(atomic.LoadPointer(&this.m.eng))
}
func (this *Segment) rehash() {
oldTable := this.table() //*(*[]*Entry)(this.table)
oldCapacity := len(oldTable)
if oldCapacity >= MAXIMUM_CAPACITY {
return
}
/*
* Reclassify nodes in each list to new Map. Because we are
* using power-of-two expansion, the elements from each bin
* must either stay at same index, or move with a power of two
* offset. We eliminate unnecessary node creation by catching
* cases where old nodes can be reused because their next
* fields won't change. Statistically, at the default
* threshold, only about one-sixth of them need cloning when
* a table doubles. The nodes they replace will be garbage
* collectable as soon as they are no longer referenced by any
* reader thread that may be in the midst of traversing table
* right now.
*/
newTable := make([]unsafe.Pointer, oldCapacity<<1)
atomic.StoreInt32(&this.threshold, int32(float32(len(newTable))*this.loadFactor))
sizeMask := uint32(len(newTable) - 1)
for i := 0; i < oldCapacity; i++ {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet nil out each bin.
e := (*Entry)(oldTable[i])
if e != nil {
next := e.next
//计算节点扩容后新的数组下标
idx := e.hash & sizeMask
// Single node on list
//如果没有后续的碰撞节点,直接复制到新数组即可
if next == nil {
newTable[idx] = unsafe.Pointer(e)
} else {
/* Reuse trailing consecutive sequence at same slot
* 数组扩容后原来数组下标相同(碰撞)的节点可能会计算出不同的新下标
* 如果把碰撞链表中所有节点的新下标列出,并将相邻的新下标相同的节点视为一段
* 那么下面的代码为了提高效率,会循环碰撞链表,找到链表中最后一段首节点(之后所有节点的新下标相同)
* 然后将这个首节点复制到新数组,后续节点因为计算出的新下标相同,所以在扩容后的数组中仍然在同一碰撞链表中
* 所以新的首节点的碰撞链表是正确的
* 新的首节点之外的其他现存碰撞链表上的节点,则重新复制到新节点(这个重要,可以保持旧节点的不变性)后放入新数组
* 这个过程的关键在于维持所有旧节点的next属性不会发生变化,这样才能让无锁的读操作保持线程安全
*/
lastRun := e
lastIdx := idx
for last := next; last != nil; last = last.next {
k := last.hash & uint32(sizeMask)
//发现新下标不同的节点就保存到lastIdx和lastRun中
//所以lastIdx和lastRun总是对应现有碰撞链表中最后一段新下标相同节点的首节点和其对应的新下标
if k != lastIdx {
lastIdx = k
lastRun = last
}
}
newTable[lastIdx] = unsafe.Pointer(lastRun)
// Clone all remaining nodes
for p := e; p != lastRun; p = p.next {
k := p.hash & sizeMask
n := newTable[k]
newTable[k] = unsafe.Pointer(&Entry{p.key, p.hash, p.value, (*Entry)(n)})
}
}
}
}
atomic.StorePointer(&this.pTable, unsafe.Pointer(&newTable))
}
/**
* Sets table to new pointer slice that all item points to HashEntry.
* Call only while holding lock or in constructor.
*/
func (this *Segment) setTable(newTable []unsafe.Pointer) {
this.threshold = (int32)(float32(len(newTable)) * this.loadFactor)
this.pTable = unsafe.Pointer(&newTable)
}
/**
* uses atomic to load table and returns.
* Call while no lock.
*/
func (this *Segment) loadTable() (table []unsafe.Pointer) {
return *(*[]unsafe.Pointer)(atomic.LoadPointer(&this.pTable))
}
/**
* returns pointer slice that all item points to HashEntry.
* Call only while holding lock or in constructor.
*/
func (this *Segment) table() []unsafe.Pointer {
return *(*[]unsafe.Pointer)(this.pTable)
}
/**
* Returns properly casted first entry of bin for given hash.
*/
func (this *Segment) getFirst(hash uint32) *Entry {
tab := this.loadTable()
return (*Entry)(atomic.LoadPointer(&tab[hash&uint32(len(tab)-1)]))
}
/**
* Reads value field of an entry under lock. Called if value
* field ever appears to be nil. see below code:
* tab[index] = unsafe.Pointer(&Entry{key, hash, unsafe.Pointer(&value), first})
* go memory model don't explain Entry initialization must be executed before
* table assignment. So value is nil is possible only if a
* compiler happens to reorder a HashEntry initialization with
* its table assignment, which is legal under memory model
* but is not known to ever occur.
*/
func (this *Segment) readValueUnderLock(e *Entry) interface{} {
this.lock.Lock()
defer this.lock.Unlock()
return e.fastValue()
}
/* Specialized implementations of map methods */
func (this *Segment) get(key interface{}, hash uint32) interface{} {
if atomic.LoadInt32(&this.count) != 0 { // atomic-read
e := this.getFirst(hash)
for e != nil {
if e.hash == hash && equals(e.key, key) {
v := e.Value()
if v != nil {
//return
return v
}
return this.readValueUnderLock(e) // recheck
}
e = e.next
}
}
return nil
}
func (this *Segment) containsKey(key interface{}, hash uint32) bool {
if atomic.LoadInt32(&this.count) != 0 { // read-volatile
e := this.getFirst(hash)
for e != nil {
if e.hash == hash && equals(e.key, key) {
return true
}
e = e.next
}
}
return false
}
func (this *Segment) compareAndReplace(key interface{}, hash uint32, oldVal interface{}, newVal interface{}) bool {
this.lock.Lock()
defer this.lock.Unlock()
e := this.getFirst(hash)
for e != nil && (e.hash != hash || !equals(e.key, key)) {
e = e.next
}
replaced := false
if e != nil && oldVal == e.fastValue() {
replaced = true
e.storeValue(&newVal)
}
return replaced
}
func (this *Segment) replace(key interface{}, hash uint32, newVal interface{}) (oldVal interface{}) {
this.lock.Lock()
defer this.lock.Unlock()
e := this.getFirst(hash)
for e != nil && (e.hash != hash || !equals(e.key, key)) {
e = e.next
}
if e != nil {
oldVal = e.fastValue()
e.storeValue(&newVal)
}
return
}
/**
* put方法牵涉到count, modCount, pTable三个共享变量的修改
* 在Java中count和pTable是volatile字段,而modCount不是
* 由于IsEmpty和Size等操作会读取count, modCount和pTable并且是无锁的,这里有必要对进行并发安全性的分析
* 在Java中,volatile的读具有Acquire语义,volatile的写具有release语义,而put的最后会写入count,
* 其他读操作总是会先读取count,由此保证了put中其他的写入操作不会被reorder到写入count之后,而读操作中其他的读取不会被reorder到读count之前
* 由此保证了多线程情况下读和写线程中看到的操作次序不会发送混乱,
* 在Golang中,StorePointer内部使用了xchgl指令,具有内存屏障,但是Load操作似乎并未具有明确的acquire语义
*/
func (this *Segment) put(key interface{}, hash uint32, value interface{}, onlyIfAbsent bool, action func(oldValue interface{}) (newVal interface{})) (oldValue interface{}) {
this.lock.Lock()
defer this.lock.Unlock()
c := this.count
if c > this.threshold { // ensure capacity
this.rehash()
}
tab := this.table()
index := hash & uint32(len(tab)-1)
first := (*Entry)(tab[index])
e := first
for e != nil && (e.hash != hash || !equals(e.key, key)) {
e = e.next
}
if action == nil {
if e != nil {
oldValue = e.fastValue()
if !onlyIfAbsent {
e.storeValue(&value)
}
} else {
c++
oldValue = nil
this.modCount++
tab[index] = unsafe.Pointer(&Entry{key, hash, unsafe.Pointer(&value), first})
atomic.StoreInt32(&this.count, c) // atomic write 这里可以保证对modCount和tab的修改不会被reorder到this.count之后
}
} else {
if e != nil {
oldValue = e.fastValue()
} else {
c++
oldValue = nil
}
newVal := action(oldValue)
if newVal != nil {
if oldValue == nil {
e = &Entry{key, hash, unsafe.Pointer(&value), first}
tab[index] = unsafe.Pointer(e)
this.modCount++
atomic.StoreInt32(&this.count, c) // atomic write 这里可以保证对modCount和tab的修改不会被reorder到this.count之后