Skip to content

Commit 9cd551b

Browse files
committed
ring buffer
1 parent afb6302 commit 9cd551b

File tree

3 files changed

+105
-3
lines changed

3 files changed

+105
-3
lines changed

src/main/java/code/algorithm/search/BinarySearch.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
package code.algorithm.search;
22

3-
import org.apache.commons.lang3.tuple.Pair;
4-
53
import java.util.Arrays;
64

75
/**
86
* 〈二分查找〉<p>
9-
* 〈功能详细描述〉
7+
* 最坏时间复杂度:O(log n)
108
*
119
* @author zixiao
1210
* @date 2019/11/27
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)