jaulib v1.3.0
Jau Support Library (C++, Java, ..)
LFRingbuffer.java
Go to the documentation of this file.
1/**
2 * Author: Sven Gothel <sgothel@jausoft.com>
3 * Copyright (c) 2020 Gothel Software e.K.
4 * Copyright (c) 2013 Gothel Software e.K.
5 * Copyright (c) 2013 JogAmp Community.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining
8 * a copy of this software and associated documentation files (the
9 * "Software"), to deal in the Software without restriction, including
10 * without limitation the rights to use, copy, modify, merge, publish,
11 * distribute, sublicense, and/or sell copies of the Software, and to
12 * permit persons to whom the Software is furnished to do so, subject to
13 * the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be
16 * included in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 */
26
27package org.jau.util;
28
29import java.io.PrintStream;
30import java.lang.reflect.Array;
31
32/**
33 * Simple implementation of {@link Ringbuffer},
34 * exposing <i>lock-free</i>
35 * {@link #get() get*(..)} and {@link #put(Object) put*(..)} methods.
36 * <p>
37 * Implementation utilizes the <i>Always Keep One Slot Open</i>,
38 * hence implementation maintains an internal array of <code>capacity</code> <i>plus one</i>!
39 * </p>
40 * <p>
41 * Implementation is thread safe if:
42 * <ul>
43 * <li>{@link #get() get*(..)} operations are performed from one thread only.</li>
44 * <li>{@link #put(Object) put*(..)} operations are performed from one thread only.</li>
45 * <li>{@link #get() get*(..)} and {@link #put(Object) put*(..)} thread may be the same.</li>
46 * </ul>
47 * </p>
48 * <p>
49 * Following methods utilize global synchronization:
50 * <ul>
51 * <li>{@link #resetFull(Object[])}</li>
52 * <li>{@link #clear()}</li>
53 * <li>{@link #growEmptyBuffer(Object[])}</li>
54 * </ul>
55 * User needs to synchronize above methods w/ the lock-free
56 * w/ {@link #get() get*(..)} and {@link #put(Object) put*(..)} methods,
57 * e.g. by controlling their threads before invoking the above.
58 * </p>
59 * <p>
60 * Characteristics:
61 * <ul>
62 * <li>Read position points to the last read element.</li>
63 * <li>Write position points to the last written element.</li>
64 * </ul>
65 * <table border="1">
66 * <tr><td>Empty</td><td>writePos == readPos</td><td>size == 0</td></tr>
67 * <tr><td>Full</td><td>writePos == readPos - 1</td><td>size == capacity</td></tr>
68 * </table>
69 * </p>
70 */
71public class LFRingbuffer<T> implements Ringbuffer<T> {
72
73 private final Object syncRead = new Object();
74 private final Object syncWrite = new Object();
75 private final Object syncGlobal = new Object();
76 private /* final */ volatile T[] array; // not final due to grow
77 private /* final */ volatile int capacityPlusOne; // not final due to grow
78 private volatile int readPos;
79 private volatile int writePos;
80 private volatile int size;
81
82 @Override
83 public final String toString() {
84 return "LFRingbuffer<?>[filled "+size+" / "+(capacityPlusOne-1)+", writePos "+writePos+", readPos "+readPos+"]";
85 }
86
87 @Override
88 public final void dump(final PrintStream stream, final String prefix) {
89 stream.println(prefix+" "+toString()+" {");
90 for(int i=0; i<capacityPlusOne; i++) {
91 stream.println("\t["+i+"]: "+array[i]);
92 }
93 stream.println("}");
94 }
95
96 /**
97 * Create a full ring buffer instance w/ the given array's net capacity and content.
98 * <p>
99 * Example for a 10 element Integer array:
100 * <pre>
101 * Integer[] source = new Integer[10];
102 * // fill source with content ..
103 * Ringbuffer<Integer> rb = new LFRingbuffer<Integer>(source);
104 * </pre>
105 * </p>
106 * <p>
107 * {@link #isFull()} returns true on the newly created full ring buffer.
108 * </p>
109 * <p>
110 * Implementation will allocate an internal array with size of array <code>copyFrom</code> <i>plus one</i>,
111 * and copy all elements from array <code>copyFrom</code> into the internal array.
112 * </p>
113 * @param copyFrom mandatory source array determining ring buffer's net {@link #capacity()} and initial content.
114 * @throws IllegalArgumentException if <code>copyFrom</code> is <code>null</code>
115 */
116 @SuppressWarnings("unchecked")
117 public LFRingbuffer(final T[] copyFrom) throws IllegalArgumentException {
118 capacityPlusOne = copyFrom.length + 1;
119 array = (T[]) newArray(copyFrom.getClass(), capacityPlusOne);
120 resetImpl(true, copyFrom);
121 }
122
123 /**
124 * Create an empty ring buffer instance w/ the given net <code>capacity</code>.
125 * <p>
126 * Example for a 10 element Integer array:
127 * <pre>
128 * Ringbuffer<Integer> rb = new LFRingbuffer<Integer>(10, Integer[].class);
129 * </pre>
130 * </p>
131 * <p>
132 * {@link #isEmpty()} returns true on the newly created empty ring buffer.
133 * </p>
134 * <p>
135 * Implementation will allocate an internal array of size <code>capacity</code> <i>plus one</i>.
136 * </p>
137 * @param arrayType the array type of the created empty internal array.
138 * @param capacity the initial net capacity of the ring buffer
139 */
140 public LFRingbuffer(final Class<? extends T[]> arrayType, final int capacity) {
141 capacityPlusOne = capacity+1;
142 array = newArray(arrayType, capacityPlusOne);
143 resetImpl(false, null /* empty, nothing to copy */ );
144 }
145
146 @Override
147 public final int capacity() { return capacityPlusOne-1; }
148
149 @Override
150 public final void clear() {
151 synchronized ( syncGlobal ) {
152 resetImpl(false, null);
153 for(int i=0; i<capacityPlusOne; i++) {
154 this.array[i] = null;
155 }
156 }
157 }
158
159 @Override
160 public final void resetFull(final T[] copyFrom) throws IllegalArgumentException {
161 resetImpl(true, copyFrom);
162 }
163
164 private final void resetImpl(final boolean full, final T[] copyFrom) throws IllegalArgumentException {
165 synchronized ( syncGlobal ) {
166 if( null != copyFrom ) {
167 if( copyFrom.length != capacityPlusOne-1 ) {
168 throw new IllegalArgumentException("copyFrom array length "+copyFrom.length+" != capacity "+this);
169 }
170 System.arraycopy(copyFrom, 0, array, 0, copyFrom.length);
171 array[capacityPlusOne-1] = null; // null 'plus-one' field!
172 } else if ( full ) {
173 throw new IllegalArgumentException("copyFrom array is null");
174 }
175 readPos = capacityPlusOne - 1;
176 if( full ) {
177 writePos = readPos - 1;
178 size = capacityPlusOne - 1;
179 } else {
180 writePos = readPos;
181 size = 0;
182 }
183 }
184 }
185
186 @Override
187 public final int size() { return size; }
188
189 @Override
190 public final int getFreeSlots() { return capacityPlusOne - 1 - size; }
191
192 @Override
193 public final boolean isEmpty() { return 0 == size; }
194
195 @Override
196 public final boolean isFull() { return capacityPlusOne - 1 == size; }
197
198 /**
199 * {@inheritDoc}
200 * <p>
201 * Implementation advances the read position and returns the element at it, if not empty.
202 * </p>
203 */
204 @Override
205 public final T get() {
206 try {
207 return getImpl(false, false);
208 } catch (final InterruptedException ie) { throw new RuntimeException(ie); }
209 }
210
211 /**
212 * {@inheritDoc}
213 * <p>
214 * Implementation advances the read position and returns the element at it, if not empty.
215 * </p>
216 */
217 @Override
218 public final T getBlocking() throws InterruptedException {
219 return getImpl(true, false);
220 }
221
222 @Override
223 public final T peek() {
224 try {
225 return getImpl(false, true);
226 } catch (final InterruptedException ie) { throw new RuntimeException(ie); }
227 }
228 @Override
229 public final T peekBlocking() throws InterruptedException {
230 return getImpl(true, true);
231 }
232
233 private final T getImpl(final boolean blocking, final boolean peek) throws InterruptedException {
234 int localReadPos = readPos;
235 if( localReadPos == writePos ) {
236 if( blocking ) {
237 synchronized( syncRead ) {
238 while( localReadPos == writePos ) {
239 syncRead.wait();
240 }
241 }
242 } else {
243 return null;
244 }
245 }
246 localReadPos = (localReadPos + 1) % capacityPlusOne;
247 final T r = array[localReadPos];
248 if( !peek ) {
249 array[localReadPos] = null;
250 synchronized ( syncWrite ) {
251 size--;
252 readPos = localReadPos;
253 syncWrite.notifyAll(); // notify waiting putter
254 }
255 }
256 return r;
257 }
258
259 /**
260 * {@inheritDoc}
261 * <p>
262 * Implementation advances the write position and stores the given element at it, if not full.
263 * </p>
264 */
265 @Override
266 public final boolean put(final T e) {
267 try {
268 return putImpl(e, false, false);
269 } catch (final InterruptedException ie) { throw new RuntimeException(ie); }
270 }
271
272 /**
273 * {@inheritDoc}
274 * <p>
275 * Implementation advances the write position and stores the given element at it, if not full.
276 * </p>
277 */
278 @Override
279 public final void putBlocking(final T e) throws InterruptedException {
280 if( !putImpl(e, false, true) ) {
281 throw new InternalError("Blocking put failed: "+this);
282 }
283 }
284
285 /**
286 * {@inheritDoc}
287 * <p>
288 * Implementation advances the write position and keeps the element at it, if not full.
289 * </p>
290 */
291 @Override
292 public final boolean putSame(final boolean blocking) throws InterruptedException {
293 return putImpl(null, true, blocking);
294 }
295
296 private final boolean putImpl(final T e, final boolean sameRef, final boolean blocking) throws InterruptedException {
297 int localWritePos = writePos;
298 localWritePos = (localWritePos + 1) % capacityPlusOne;
299 if( localWritePos == readPos ) {
300 if( blocking ) {
301 synchronized( syncWrite ) {
302 while( localWritePos == readPos ) {
303 syncWrite.wait();
304 }
305 }
306 } else {
307 return false;
308 }
309 }
310 if( !sameRef ) {
311 array[localWritePos] = e;
312 }
313 synchronized ( syncRead ) {
314 size++;
315 writePos = localWritePos;
316 syncRead.notifyAll(); // notify waiting getter
317 }
318 return true;
319 }
320
321
322 @Override
323 public final void waitForFreeSlots(final int count) throws InterruptedException {
324 synchronized ( syncRead ) {
325 if( capacityPlusOne - 1 - size < count ) {
326 while( capacityPlusOne - 1 - size < count ) {
327 syncRead.wait();
328 }
329 }
330 }
331 }
332
333 @Override
334 public final void growEmptyBuffer(final T[] newElements) throws IllegalStateException, IllegalArgumentException {
335 synchronized( syncGlobal ) {
336 if( null == newElements ) {
337 throw new IllegalArgumentException("newElements is null");
338 }
339 @SuppressWarnings("unchecked")
340 final Class<? extends T[]> arrayTypeInternal = (Class<? extends T[]>) array.getClass();
341 @SuppressWarnings("unchecked")
342 final Class<? extends T[]> arrayTypeNew = (Class<? extends T[]>) newElements.getClass();
343 if( arrayTypeInternal != arrayTypeNew ) {
344 throw new IllegalArgumentException("newElements array-type mismatch, internal "+arrayTypeInternal+", newElements "+arrayTypeNew);
345 }
346 if( 0 != size ) {
347 throw new IllegalStateException("Buffer is not empty: "+this);
348 }
349 if( readPos != writePos ) {
350 throw new InternalError("R/W pos not equal: "+this);
351 }
352 if( readPos != writePos ) {
353 throw new InternalError("R/W pos not equal at empty: "+this);
354 }
355
356 final int growAmount = newElements.length;
357 final int newCapacity = capacityPlusOne + growAmount;
358 final T[] oldArray = array;
359 final T[] newArray = newArray(arrayTypeInternal, newCapacity);
360
361 // writePos == readPos
362 writePos += growAmount; // warp writePos to the end of the new data location
363
364 if( readPos >= 0 ) {
365 System.arraycopy(oldArray, 0, newArray, 0, readPos+1);
366 }
367 if( growAmount > 0 ) {
368 System.arraycopy(newElements, 0, newArray, readPos+1, growAmount);
369 }
370 final int tail = capacityPlusOne-1-readPos;
371 if( tail > 0 ) {
372 System.arraycopy(oldArray, readPos+1, newArray, writePos+1, tail);
373 }
374 size = growAmount;
375
376 capacityPlusOne = newCapacity;
377 array = newArray;
378 }
379 }
380
381 @Override
382 public final void growFullBuffer(final int growAmount) throws IllegalStateException, IllegalArgumentException {
383 synchronized ( syncGlobal ) {
384 if( 0 > growAmount ) {
385 throw new IllegalArgumentException("amount "+growAmount+" < 0 ");
386 }
387 if( capacityPlusOne-1 != size ) {
388 throw new IllegalStateException("Buffer is not full: "+this);
389 }
390 final int wp1 = ( writePos + 1 ) % capacityPlusOne;
391 if( wp1 != readPos ) {
392 throw new InternalError("R != W+1 pos at full: "+this);
393 }
394 @SuppressWarnings("unchecked")
395 final Class<? extends T[]> arrayTypeInternal = (Class<? extends T[]>) array.getClass();
396
397 final int newCapacity = capacityPlusOne + growAmount;
398 final T[] oldArray = array;
399 final T[] newArray = newArray(arrayTypeInternal, newCapacity);
400
401 // writePos == readPos - 1
402 readPos = ( writePos + 1 + growAmount ) % newCapacity; // warp readPos to the end of the new data location
403
404 if(writePos >= 0) {
405 System.arraycopy(oldArray, 0, newArray, 0, writePos+1);
406 }
407 final int tail = capacityPlusOne-1-writePos;
408 if( tail > 0 ) {
409 System.arraycopy(oldArray, writePos+1, newArray, readPos, tail);
410 }
411
412 capacityPlusOne = newCapacity;
413 array = newArray;
414 }
415 }
416
417 @SuppressWarnings("unchecked")
418 private static <T> T[] newArray(final Class<? extends T[]> arrayType, final int length) {
419 return ((Object)arrayType == (Object)Object[].class)
420 ? (T[]) new Object[length]
421 : (T[]) Array.newInstance(arrayType.getComponentType(), length);
422 }
423}
Simple implementation of Ringbuffer, exposing lock-free get*(..) and put*(..) methods.
final void clear()
Resets the read and write position according to an empty ring buffer and set all ring buffer slots to...
final void waitForFreeSlots(final int count)
Blocks until at least count free slots become available.
final boolean putSame(final boolean blocking)
Enqueues the same element at it's write position, if not full.Returns true if successful,...
final void resetFull(final T[] copyFrom)
Resets the read and write position according to a full ring buffer and fill all slots w/ elements of ...
LFRingbuffer(final Class<? extends T[]> arrayType, final int capacity)
Create an empty ring buffer instance w/ the given net capacity.
final boolean isFull()
Returns true if this ring buffer is full, otherwise false.
final boolean put(final T e)
Enqueues the given element.Returns true if successful, otherwise false in case buffer is full....
final boolean isEmpty()
Returns true if this ring buffer is empty, otherwise false.
final T getBlocking()
Dequeues the oldest enqueued element.The returned ring buffer slot will be set to null to release the...
final void putBlocking(final T e)
Enqueues the given element.Method blocks until a free slot becomes available via get.
final void growEmptyBuffer(final T[] newElements)
Grows an empty ring buffer, increasing it's capacity about the amount.
final int size()
Returns the number of elements in this ring buffer.
final int getFreeSlots()
Returns the number of free slots available to put.
final void dump(final PrintStream stream, final String prefix)
Debug functionality - Dumps the contents of the internal array.
final int capacity()
Returns the net capacity of this ring buffer.
final T peek()
Peeks the next element at the read position w/o modifying pointer, nor blocking.
final T peekBlocking()
Peeks the next element at the read position w/o modifying pointer, but w/ blocking.
final void growFullBuffer(final int growAmount)
Grows a full ring buffer, increasing it's capacity about the amount.
final String toString()
Returns a short string representation incl.
Ring buffer interface, a.k.a circular buffer.
Definition: Ringbuffer.java:43