File tree Expand file tree Collapse file tree 3 files changed +105
-3
lines changed Expand file tree Collapse file tree 3 files changed +105
-3
lines changed Original file line number Diff line number Diff line change 11package code .algorithm .search ;
22
3- import org .apache .commons .lang3 .tuple .Pair ;
4-
53import java .util .Arrays ;
64
75/**
86 * 〈二分查找〉<p>
9- * 〈功能详细描述〉
7+ * 最坏时间复杂度:O(log n)
108 *
119 * @author zixiao
1210 * @date 2019/11/27
Original file line number Diff line number Diff line change 1+ package code .collection .ringbuffer ;
2+
3+ /**
4+ * 〈环形缓冲区〉<p>
5+ * 〈功能详细描述〉
6+ *
7+ * @author zixiao
8+ * @date 2019/12/23
9+ */
10+ public class RingBuffer <E > {
11+
12+ private int bufferSize ;
13+
14+ private Object [] entries ;
15+
16+ private final int indexMask ;
17+
18+ private final Sequencer sequencer ;
19+
20+ public RingBuffer (int bufferSize ) {
21+ if (Integer .bitCount (bufferSize ) != 1 ) {
22+ this .bufferSize = get2Power (bufferSize );
23+ } else {
24+ this .bufferSize = bufferSize ;
25+ }
26+ this .indexMask = bufferSize - 1 ;
27+ this .entries = new Object [this .bufferSize ];
28+ this .sequencer = new Sequencer (this .bufferSize );
29+ }
30+
31+ private int get2Power (int capacity ) {
32+ int n = capacity - 1 ;
33+ n |= n >>> 1 ;
34+ n |= n >>> 2 ;
35+ n |= n >>> 4 ;
36+ n |= n >>> 8 ;
37+ n |= n >>> 16 ;
38+ return n + 1 ;
39+ }
40+
41+ public E get (long seq ){
42+ Long idx = seq & indexMask ;
43+ return (E )entries [idx .intValue ()];
44+ }
45+
46+ public long next () {
47+ return sequencer .next ();
48+ }
49+
50+ public long next (int n ) {
51+ return sequencer .next (n );
52+ }
53+
54+ }
Original file line number Diff line number Diff line change 1+ package code .collection .ringbuffer ;
2+
3+ import java .util .concurrent .atomic .AtomicLong ;
4+
5+ /**
6+ * 〈一句话功能简述〉<p>
7+ * 〈功能详细描述〉
8+ *
9+ * @author zixiao
10+ * @date 2019/12/23
11+ */
12+ public class Sequencer {
13+
14+ protected final int bufferSize ;
15+
16+ // 使用sequence代替,实现缓存行填充来消除伪共享
17+ private final AtomicLong cursor = new AtomicLong (-1 );
18+
19+ private final int [] availableBuffer ;
20+
21+ private final int indexMask ;
22+
23+ public Sequencer (int bufferSize ) {
24+ this .bufferSize = bufferSize ;
25+ if (Integer .bitCount (bufferSize ) != 1 ){
26+ throw new IllegalArgumentException ("bufferSize must be a power of 2" );
27+ }
28+ availableBuffer = new int [this .bufferSize ];
29+ indexMask = this .bufferSize - 1 ;
30+ }
31+
32+ public long next (){
33+ return next (1 );
34+ }
35+
36+ public long next (int n ) {
37+ long current = cursor .get ();
38+ long next ;
39+ do {
40+ next = current + n ;
41+ // CAS申请n个位置
42+ if (cursor .compareAndSet (current , next )) {
43+ break ;
44+ }
45+ } while (true );
46+ return next ;
47+ }
48+
49+
50+ }
You can’t perform that action at this time.
0 commit comments