1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.baidu.fsg.uid.buffer;
17
18 import java.util.concurrent.atomic.AtomicLong;
19
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.springframework.util.Assert;
23
24 import com.baidu.fsg.uid.utils.PaddedAtomicLong;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 public class RingBuffer {
40 private static final Logger LOGGER = LoggerFactory.getLogger(RingBuffer.class);
41
42
43 private static final int START_POINT = -1;
44 private static final long CAN_PUT_FLAG = 0L;
45 private static final long CAN_TAKE_FLAG = 1L;
46 public static final int DEFAULT_PADDING_PERCENT = 50;
47
48
49 private final int bufferSize;
50 private final long indexMask;
51 private final long[] slots;
52 private final PaddedAtomicLong[] flags;
53
54
55 private final AtomicLong tail = new PaddedAtomicLong(START_POINT);
56
57
58 private final AtomicLong cursor = new PaddedAtomicLong(START_POINT);
59
60
61 private final int paddingThreshold;
62
63
64 private RejectedPutBufferHandler rejectedPutHandler = this::discardPutBuffer;
65 private RejectedTakeBufferHandler rejectedTakeHandler = this::exceptionRejectedTakeBuffer;
66
67
68 private BufferPaddingExecutor bufferPaddingExecutor;
69
70
71
72
73
74
75 public RingBuffer(int bufferSize) {
76 this(bufferSize, DEFAULT_PADDING_PERCENT);
77 }
78
79
80
81
82
83
84
85
86
87 public RingBuffer(int bufferSize, int paddingFactor) {
88
89 Assert.isTrue(bufferSize > 0L, "RingBuffer size must be positive");
90 Assert.isTrue(Integer.bitCount(bufferSize) == 1, "RingBuffer size must be a power of 2");
91 Assert.isTrue(paddingFactor > 0 && paddingFactor < 100, "RingBuffer size must be positive");
92
93 this.bufferSize = bufferSize;
94 this.indexMask = bufferSize - 1;
95 this.slots = new long[bufferSize];
96 this.flags = initFlags(bufferSize);
97
98 this.paddingThreshold = bufferSize * paddingFactor / 100;
99 }
100
101
102
103
104
105
106
107
108
109
110
111 public synchronized boolean put(long uid) {
112 long currentTail = tail.get();
113 long currentCursor = cursor.get();
114
115
116 long distance = currentTail - (currentCursor == START_POINT ? 0 : currentCursor);
117 if (distance == bufferSize - 1) {
118 rejectedPutHandler.rejectPutBuffer(this, uid);
119 return false;
120 }
121
122
123 int nextTailIndex = calSlotIndex(currentTail + 1);
124 if (flags[nextTailIndex].get() != CAN_PUT_FLAG) {
125 rejectedPutHandler.rejectPutBuffer(this, uid);
126 return false;
127 }
128
129
130
131
132 slots[nextTailIndex] = uid;
133 flags[nextTailIndex].set(CAN_TAKE_FLAG);
134 tail.incrementAndGet();
135
136
137
138 return true;
139 }
140
141
142
143
144
145
146
147
148
149
150
151 public long take() {
152
153 long currentCursor = cursor.get();
154 long nextCursor = cursor.updateAndGet(old -> old == tail.get() ? old : old + 1);
155
156
157 Assert.isTrue(nextCursor >= currentCursor, "Curosr can't move back");
158
159
160 long currentTail = tail.get();
161 if (currentTail - nextCursor < paddingThreshold) {
162 LOGGER.info("Reach the padding threshold:{}. tail:{}, cursor:{}, rest:{}", paddingThreshold, currentTail,
163 nextCursor, currentTail - nextCursor);
164 bufferPaddingExecutor.asyncPadding();
165 }
166
167
168 if (nextCursor == currentCursor) {
169 rejectedTakeHandler.rejectTakeBuffer(this);
170 }
171
172
173 int nextCursorIndex = calSlotIndex(nextCursor);
174 Assert.isTrue(flags[nextCursorIndex].get() == CAN_TAKE_FLAG, "Curosr not in can take status");
175
176
177
178 long uid = slots[nextCursorIndex];
179 flags[nextCursorIndex].set(CAN_PUT_FLAG);
180
181
182
183 return uid;
184 }
185
186
187
188
189 protected int calSlotIndex(long sequence) {
190 return (int) (sequence & indexMask);
191 }
192
193
194
195
196 protected void discardPutBuffer(RingBuffer ringBuffer, long uid) {
197 LOGGER.warn("Rejected putting buffer for uid:{}. {}", uid, ringBuffer);
198 }
199
200
201
202
203 protected void exceptionRejectedTakeBuffer(RingBuffer ringBuffer) {
204 LOGGER.warn("Rejected take buffer. {}", ringBuffer);
205 throw new RuntimeException("Rejected take buffer. " + ringBuffer);
206 }
207
208
209
210
211 private PaddedAtomicLong[] initFlags(int bufferSize) {
212 PaddedAtomicLong[] flags = new PaddedAtomicLong[bufferSize];
213 for (int i = 0; i < bufferSize; i++) {
214 flags[i] = new PaddedAtomicLong(CAN_PUT_FLAG);
215 }
216
217 return flags;
218 }
219
220
221
222
223 public long getTail() {
224 return tail.get();
225 }
226
227 public long getCursor() {
228 return cursor.get();
229 }
230
231 public int getBufferSize() {
232 return bufferSize;
233 }
234
235
236
237
238 public void setBufferPaddingExecutor(BufferPaddingExecutor bufferPaddingExecutor) {
239 this.bufferPaddingExecutor = bufferPaddingExecutor;
240 }
241
242 public void setRejectedPutHandler(RejectedPutBufferHandler rejectedPutHandler) {
243 this.rejectedPutHandler = rejectedPutHandler;
244 }
245
246 public void setRejectedTakeHandler(RejectedTakeBufferHandler rejectedTakeHandler) {
247 this.rejectedTakeHandler = rejectedTakeHandler;
248 }
249
250 @Override
251 public String toString() {
252 StringBuilder builder = new StringBuilder();
253 builder.append("RingBuffer [bufferSize=").append(bufferSize)
254 .append(", tail=").append(tail)
255 .append(", cursor=").append(cursor)
256 .append(", paddingThreshold=").append(paddingThreshold).append("]");
257
258 return builder.toString();
259 }
260
261 }