Skip to content

Commit fd5e325

Browse files
[Java] Add example usage to RingBuffer
1 parent a0064c8 commit fd5e325

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

agrona/src/main/java/org/agrona/concurrent/ringbuffer/RingBuffer.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,65 @@
2121
/**
2222
* Ring-buffer for the concurrent exchanging of binary encoded messages from producer(s) to consumer(s)
2323
* in a FIFO manner.
24+
* <p>
25+
* Example usage with write method:
26+
* <pre>
27+
* // Create a ring buffer with a direct buffer of 1024 bytes
28+
* ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
29+
* RingBuffer ringBuffer = new OneToOneRingBuffer(new UnsafeBuffer(byteBuffer));
30+
*
31+
* // Pre-allocate a reusable buffer (cached for the lifetime of the writer)
32+
* MutableDirectBuffer srcBuffer = new UnsafeBuffer(ByteBuffer.allocateDirect(Long.BYTES));
33+
*
34+
* // Write a message using the cached buffer
35+
* srcBuffer.putLong(0, 12345L);
36+
* if (!ringBuffer.write(1, srcBuffer, 0, Long.BYTES))
37+
* {
38+
* // Handle insufficient capacity (e.g., retry, log, or drop message)
39+
* System.err.println("Failed to write message: insufficient capacity");
40+
* }
41+
*
42+
* // Read the message
43+
* ringBuffer.read((msgTypeId, buffer, index, msgLength) -> {
44+
* long value = buffer.getLong(index);
45+
* System.out.println("Received: " + value);
46+
* });
47+
* </pre>
48+
* <p>
49+
* Example usage with tryClaim for zero-copy writes:
50+
* <pre>
51+
* // Create a ring buffer
52+
* ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
53+
* RingBuffer ringBuffer = new OneToOneRingBuffer(new UnsafeBuffer(byteBuffer));
54+
*
55+
* // Claim space and write directly to the ring buffer (zero-copy)
56+
* final int index = ringBuffer.tryClaim(1, Long.BYTES);
57+
* if (index > 0)
58+
* {
59+
* try
60+
* {
61+
* final AtomicBuffer buffer = ringBuffer.buffer();
62+
* buffer.putLong(index, 12345L);
63+
* ringBuffer.commit(index);
64+
* }
65+
* catch (final Exception ex)
66+
* {
67+
* ringBuffer.abort(index);
68+
* throw ex;
69+
* }
70+
* }
71+
* else
72+
* {
73+
* // Handle insufficient capacity
74+
* System.err.println("Failed to claim space: insufficient capacity");
75+
* }
76+
*
77+
* // Read the message
78+
* ringBuffer.read((msgTypeId, buffer, index, msgLength) -> {
79+
* long value = buffer.getLong(index);
80+
* System.out.println("Received: " + value);
81+
* });
82+
* </pre>
2483
*/
2584
public interface RingBuffer
2685
{

0 commit comments

Comments
 (0)