### Complete DeadlineTimerWheel Usage Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DeadlineTimerWheel.md Demonstrates the full lifecycle of using DeadlineTimerWheel, including initialization, scheduling tasks with specific delays, processing expired timers, and displaying all active timers. Requires basic Java setup. ```java import org.agrona.DeadlineTimerWheel; import java.util.concurrent.TimeUnit; public class TimerWheelExample { private final DeadlineTimerWheel wheel; public TimerWheelExample() { // Create wheel: 1ms resolution, 10000 ticks (10 second range) this.wheel = new DeadlineTimerWheel( TimeUnit.MILLISECONDS, System.currentTimeMillis(), 1, // 1ms per tick 10000 // 10000 ticks ); } public void scheduleTask(String taskName, long delayMs) { long now = System.currentTimeMillis(); long deadline = now + delayMs; long registrationId = wheel.schedule(deadline, taskName.hashCode()); System.out.println("Scheduled " + taskName + " for " + deadline); } public void processExpiredTimers() { long now = System.currentTimeMillis(); int expired = wheel.poll( now, (timeUnit, currentTime, timerId) -> { System.out.println("Timer " + timerId + " expired at " + currentTime); return true; // consume the timer }, Integer.MAX_VALUE ); System.out.println("Processed " + expired + " expired timers"); } public void showAllTimers() { System.out.println("Active timers: " + wheel.timerCount()); wheel.forEach((deadline, timerId) -> { System.out.println(" Timer " + timerId + " -> " + deadline); }); } } ``` -------------------------------- ### Agent Implementation Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Example of a custom Agent implementation requiring a Queue and IdleStrategy. ```java public class MyAgent implements Agent { private final Queue queue; private final IdleStrategy idleStrategy; public MyAgent(Queue queue) { this.queue = queue; this.idleStrategy = new BackoffIdleStrategy(); } @Override public String roleName() { return "MyAgent"; } // ... implement doWork(), etc. } ``` -------------------------------- ### Complete Agent Implementation Example in Java Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Implement a message processing agent by extending the Agent interface. This example demonstrates message queuing, processing, and termination handling using AgentTerminationException. ```java import org.agrona.concurrent.Agent; import org.agrona.concurrent.AgentTerminationException; import java.util.concurrent.ConcurrentLinkedQueue; public class MessageProcessorAgent implements Agent { private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); private volatile boolean running = false; @Override public void onStart() { System.out.println("MessageProcessorAgent starting"); } @Override public int doWork() throws Exception { String message = queue.poll(); if (message == null) { // No work available return 0; } // Process the message System.out.println("Processing: " + message); // Check for termination signal if ("STOP".equals(message)) { running = false; throw new AgentTerminationException(); } // Work was done return 1; } @Override public void onClose() { System.out.println("MessageProcessorAgent closing"); queue.clear(); } @Override public String roleName() { return "MessageProcessor"; } public void submit(String message) { queue.offer(message); } } ``` -------------------------------- ### onStart() Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Called once when the agent starts, for resource initialization. The default implementation does nothing, but it can be overridden to perform initialization tasks. ```APIDOC ## onStart() ### Description Called once when the agent starts, for resource initialization. ### Method Signature ```java default void onStart() ``` ### Behavior - Called once by the agent thread at startup. - Default implementation does nothing. - Override to perform initialization tasks. ### Example ```java @Override public void onStart() { System.out.println("Agent started"); // Initialize resources } ``` ``` -------------------------------- ### RingBuffer Producer Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/RingBuffer.md Demonstrates how to use RingBuffer for sending messages. Includes both copy and zero-copy write patterns. ```java import org.agrona.concurrent.ringbuffer.*; import org.agrona.concurrent.UnsafeBuffer; import java.nio.ByteBuffer; public class RingBufferProducer { private static final int MSG_TYPE_ORDER = 1; private final RingBuffer ringBuffer; private final MutableDirectBuffer buffer; public RingBufferProducer(RingBuffer ringBuffer) { this.ringBuffer = ringBuffer; this.buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(256)); } // Pattern 1: Copy write public boolean sendOrder(int orderId, long price, int quantity) { int offset = 0; offset += buffer.putInt(offset, orderId); offset += buffer.putLong(offset, price); offset += buffer.putInt(offset, quantity); return ringBuffer.write(MSG_TYPE_ORDER, buffer, 0, offset); } // Pattern 2: Zero-copy write public boolean sendOrderZeroCopy(int orderId, long price, int quantity) { int index = ringBuffer.tryClaim(MSG_TYPE_ORDER, 16); // 4+8+4 bytes if (index > 0) { try { AtomicBuffer msgBuffer = ringBuffer.buffer(); msgBuffer.putInt(index, orderId); msgBuffer.putLong(index + 4, price); msgBuffer.putInt(index + 12, quantity); } finally { ringBuffer.commit(index); } return true; } return false; } } ``` -------------------------------- ### Agent onStart Method Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Override the onStart method to perform initialization tasks when an agent begins execution. The default implementation does nothing. ```java @Override public void onStart() { System.out.println("Agent started"); // Initialize resources } ``` -------------------------------- ### RingBuffer Consumer Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/RingBuffer.md Demonstrates how to consume messages from a RingBuffer. Implement the MessageHandler interface to process incoming messages. ```java import org.agrona.concurrent.ringbuffer.*; import org.agrona.concurrent.UnsafeBuffer; public class RingBufferConsumer implements MessageHandler { private static final int MSG_TYPE_ORDER = 1; private final RingBuffer ringBuffer; public RingBufferConsumer(RingBuffer ringBuffer) { this.ringBuffer = ringBuffer; } public void pollMessages() { ringBuffer.read(this, Integer.MAX_VALUE); } @Override public void onMessage( int msgTypeId, MutableDirectBuffer buffer, int index, int length, Header header) { if (msgTypeId == MSG_TYPE_ORDER) { int orderId = buffer.getInt(index); long price = buffer.getLong(index + 4); int quantity = buffer.getInt(index + 12); processOrder(orderId, price, quantity); } } private void processOrder(int orderId, long price, int quantity) { System.out.println("Order: " + orderId + " @ " + price + " x " + quantity); } } ``` -------------------------------- ### DirectBuffer Usage Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Demonstrates how to wrap a direct ByteBuffer with DirectBuffer, read primitive types, and perform bounds checking. Ensure the ByteBuffer is allocated directly for optimal performance. ```java import org.agrona.DirectBuffer; import org.agrona.concurrent.UnsafeBuffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; // Wrap a direct ByteBuffer ByteBuffer bb = ByteBuffer.allocateDirect(256); DirectBuffer buffer = new UnsafeBuffer(bb); // Read primitives int intValue = buffer.getInt(0); long longValue = buffer.getLong(4, ByteOrder.LITTLE_ENDIAN); String message = buffer.getStringAscii(12); // Check bounds before accessing buffer.boundsCheck(0, 8); buffer.checkLimit(256); // Get underlying objects byte[] array = buffer.byteArray(); ByteBuffer original = buffer.byteBuffer(); long address = buffer.addressOffset(); ``` -------------------------------- ### Agent Usage with AgentRunner Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Demonstrates how to start an Agent using AgentRunner, which manages the agent's lifecycle on a separate thread. Includes setting up an idle strategy and exception handler. Use this when you need the agent to run automatically in the background. ```java import org.agrona.concurrent.AgentRunner; import java.util.concurrent.Executors; MessageProcessorAgent agent = new MessageProcessorAgent(); AgentRunner runner = new AgentRunner( new BusySpinIdleStrategy(), ex -> ex.printStackTrace(), null, agent ); // Start agent on new thread Executors.newSingleThreadExecutor().execute(runner); // Submit work agent.submit("Process this"); agent.submit("STOP"); ``` -------------------------------- ### Timer Ordering Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DeadlineTimerWheel.md Demonstrates scheduling timers that may not expire in exact order due to tick resolution. Use this when precise ordering of timers within the same tick is not critical. ```java // These may not expire in exact order due to tick resolution wheel.schedule(now + 105, timerId1); // 105ms deadline wheel.schedule(now + 106, timerId2); // 106ms deadline // May expire in either order if both in same tick ``` -------------------------------- ### ExpandableDirectByteBuffer Usage Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/ExpandableDirectByteBuffer.md Demonstrates creating an ExpandableDirectByteBuffer, writing data that triggers expansion, building messages incrementally, and accessing underlying resources. Use this for scenarios where buffer size is unknown or varies significantly. ```java import org.agrona.ExpandableDirectByteBuffer; import org.agrona.MutableDirectBuffer; import java.nio.ByteOrder; // Create expandable buffer that will grow as needed MutableDirectBuffer buffer = new ExpandableDirectByteBuffer(256); // Write data that requires expansion buffer.putInt(0, 42); buffer.putLong(4, System.currentTimeMillis()); // Buffer automatically expands when writing beyond capacity for (int i = 0; i < 1000; i++) { buffer.putInt(i * 4, i); } // Useful for building messages incrementally int offset = 0; offset += buffer.putStringAscii(offset, "Header"); offset += buffer.putInt(offset, 123); offset += buffer.putStringAscii(offset, "Data"); // Get the current capacity int currentCapacity = buffer.capacity(); System.out.println("Current capacity: " + currentCapacity); // Get underlying resources java.nio.ByteBuffer bb = buffer.byteBuffer(); long addr = buffer.addressOffset(); ``` -------------------------------- ### Create a High-Throughput Ring Buffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Instantiate a RingBuffer with a direct byte buffer of a specified capacity. This example demonstrates creating a 64MB buffer suitable for high-throughput scenarios like low-latency trading. ```java // High-throughput buffer int capacity = 64 * 1024 * 1024; // 64MB RingBuffer buffer = new OneToOneRingBuffer( new UnsafeBuffer(ByteBuffer.allocateDirect(capacity)) ); ``` -------------------------------- ### Wheel Range Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DeadlineTimerWheel.md Shows how to schedule a deadline within the wheel's range. The wheel has a limited range (e.g., 1 second), and deadlines beyond this range will wrap around. Plan scheduling to stay within the wheel's coverage. ```java // Wheel: 1ms tick × 1000 ticks = 1 second range long maxDeadline = now + 1000; // Schedule within 1 second ``` -------------------------------- ### Agent roleName Method Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Implement the roleName method to return a string identifying the agent's purpose. This is useful for logging and monitoring. ```java @Override public String roleName() { return "MessageProcessor"; } ``` -------------------------------- ### Advanced Task Scheduler with DeadlineTimerWheel Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DeadlineTimerWheel.md This example demonstrates how to use DeadlineTimerWheel to schedule and process tasks with specific delays. It includes a TaskScheduler class that manages tasks and their deadlines, utilizing the wheel for efficient scheduling and polling. ```java import org.agrona.DeadlineTimerWheel; import java.util.concurrent.TimeUnit; import java.util.HashMap; import java.util.Map; public class TaskScheduler { private final DeadlineTimerWheel wheel; private final Map tasks = new HashMap<>(); private int nextTaskId = 1; public TaskScheduler() { this.wheel = new DeadlineTimerWheel( TimeUnit.MILLISECONDS, System.currentTimeMillis(), 10, // 10ms per tick 1000 // 10 second range ); } public int scheduleTask(Runnable task, long delayMs) { int taskId = nextTaskId++; long deadline = System.currentTimeMillis() + delayMs; wheel.schedule(deadline, taskId); tasks.put(taskId, new Task(task, deadline)); return taskId; } public void cancelTask(int taskId) { tasks.remove(taskId); } public void processPendingTasks() { long now = System.currentTimeMillis(); wheel.poll( now, (timeUnit, currentTime, timerId) -> { Task task = tasks.remove((int) timerId); if (task != null) { try { task.run(); } catch (Exception e) { e.printStackTrace(); } } return true; }, Integer.MAX_VALUE ); } private static class Task { private final Runnable runnable; private final long deadline; Task(Runnable runnable, long deadline) { this.runnable = runnable; this.deadline = deadline; } void run() { runnable.run(); } } } ``` -------------------------------- ### MutableDirectBuffer Usage Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/MutableDirectBuffer.md Demonstrates writing integers, longs, doubles, strings, and byte arrays to a MutableDirectBuffer. Also shows setting memory regions and checking if the buffer is expandable. Requires Agrona and standard Java libraries. ```java import org.agrona.MutableDirectBuffer; import org.agrona.concurrent.UnsafeBuffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; // Create a mutable buffer ByteBuffer bb = ByteBuffer.allocateDirect(256); M MutableDirectBuffer buffer = new UnsafeBuffer(bb); // Write primitives buffer.putInt(0, 42); buffer.putLong(4, 1234567890L, ByteOrder.LITTLE_ENDIAN); buffer.putDouble(12, 3.14); // Write strings with length prefix int written = buffer.putStringAscii(20, "Hello"); // Write ASCII encoded numbers int bytesUsed = buffer.putIntAscii(30, 42); bytesUsed = buffer.putNaturalIntAscii(35, 100); // Write bytes from another buffer byte[] data = {1, 2, 3, 4, 5}; buffer.putBytes(40, data); // Set a region to a value buffer.setMemory(50, 10, (byte) 0xFF); // Check if expandable if (buffer.isExpandable()) { // Can grow the buffer if needed } ``` -------------------------------- ### putBytes(int index, byte[] src) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/MutableDirectBuffer.md Copies an entire byte array into the underlying buffer starting at the specified index. ```APIDOC ## putBytes(int index, byte[] src) ### Description Put an array of bytes into the underlying buffer. ### Method void ### Parameters #### Path Parameters - **index** (int) - Required - Index in the underlying buffer to start from - **src** (byte[]) - Required - The byte array to copy into the buffer ``` -------------------------------- ### Robust Agent Implementation with Error Handling Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/errors.md Provides an example of an Agent implementation that handles exceptions gracefully. It re-throws AgentTerminationException and logs other exceptions while allowing the agent to continue. ```java public class RobustAgent implements Agent { @Override public int doWork() throws Exception { try { return performWork(); } catch (AgentTerminationException e) { throw e; // Re-throw termination } catch (Exception e) { logger.error("Agent error, continuing", e); return 0; // Continue despite error } } } ``` -------------------------------- ### UnsafeBuffer Capacity Check Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/UnsafeBuffer.md Demonstrates how UnsafeBuffer handles writes beyond its fixed capacity. Attempting to write past the buffer's bounds will fail or throw an exception. ```java UnsafeBuffer buffer = new UnsafeBuffer(new byte[100]); buffer.putInt(0, 42); // OK buffer.putBytes(200, data); // FAILS - beyond capacity ``` -------------------------------- ### Wrap off-heap memory by address Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Attach a view to memory located off-heap, specified by its starting memory address and length. This is for direct interaction with native memory. ```java void wrap(long address, int length) ``` -------------------------------- ### Agent onClose Method Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Override the onClose method for resource cleanup when an agent is terminated or closed. The default implementation does nothing. ```java @Override public void onClose() { resource.close(); System.out.println("Agent closed"); } ``` -------------------------------- ### Agent doWork Method Example Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Implement the doWork method to process tasks on each duty cycle. Return 0 if no work is available, or a positive value if work was completed. This method can throw exceptions to signal errors or termination. ```java @Override public int doWork() throws Exception { Message msg = queue.poll(); if (msg == null) { return 0; // No work available } processMessage(msg); return 1; // Work was done } ``` -------------------------------- ### Copy byte array to buffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/MutableDirectBuffer.md Copies an entire byte array into the buffer starting at the specified index. Ensure the buffer has enough capacity. ```java void putBytes(int index, byte[] src) ``` -------------------------------- ### Add Agrona Agent Programmatically Source: https://github.com/aeron-io/agrona/wiki/Using-Agrona-JVM-agent-for-unaligned-memory-access-discovery Include the Agrona agent directly in your code for unit testing purposes. This method requires Byte Buddy to be installed. ```java BufferAlignmentAgent.agentmain("", ByteBuddyAgent.install()); ``` -------------------------------- ### putNaturalIntAsciiFromEnd Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/MutableDirectBuffer.md Encodes an unsigned integer into ASCII bytes starting from its end position. Returns the starting index of the encoded characters. ```APIDOC ## putNaturalIntAsciiFromEnd(int value, int endExclusive) ### Description Encode a natural number starting at its end position. ### Method Signature ```java int putNaturalIntAsciiFromEnd(int value, int endExclusive) ``` ### Parameters #### Path Parameters - **value** (int) - Required - The natural number to encode - **endExclusive** (int) - Required - Index after the last character encoded ### Returns - int - The start index (inclusive) of the first character encoded. ``` -------------------------------- ### Get DirectBuffer Wrap Adjustment Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Gets the index adjustment between this buffer and its wrapped object. This is necessary for operations on the underlying byte array or byte buffer that depend on their indices. ```java int wrapAdjustment() ``` -------------------------------- ### addressOffset() Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/UnsafeBuffer.md Gets the memory address offset. This is relevant for off-heap memory access. ```APIDOC ## addressOffset() ### Description Gets the memory address offset. This is relevant for off-heap memory access. ### Method ```java public long addressOffset() ``` ### Response #### Success Response (200) - **addressOffset** (long) - Native address or array base address offset. ``` -------------------------------- ### Get DirectBuffer Address Offset Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads the memory address offset of the underlying buffer. ```java long addressOffset() ``` -------------------------------- ### Get Ring Buffer Capacity Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/RingBuffer.md Returns the total capacity of the ring buffer in bytes. ```java int capacity() ``` -------------------------------- ### Build Agrona with Gradle Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/README.md Standard Gradle commands for building the project, running tests, and generating documentation. ```bash # Full build with tests ./gradlew build ``` ```bash # Run specific tests ./gradlew test ``` ```bash # Build documentation ./gradlew javadoc ``` -------------------------------- ### roleName() Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Agent.md Get the name of this agent's role. Used for logging, monitoring, and debugging. ```APIDOC ## roleName() ### Description Get the name of this agent's role. ### Method Signature ```java String roleName() ``` ### Returns A string describing this agent's role/name. ### Behavior Used for logging, monitoring, and debugging purposes. ### Example ```java @Override public String roleName() { return "MessageProcessor"; } ``` ``` -------------------------------- ### Agent-Based System Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/README.md Demonstrates defining a simple agent that processes tasks from a queue and running it using an AgentRunner. ```java public class WorkerAgent implements Agent { private final Queue queue; @Override public int doWork() throws Exception { Task task = queue.poll(); if (task == null) return 0; // No work task.execute(); return 1; // Work done } @Override public String roleName() { return "Worker"; } } Agent agent = new WorkerAgent(queue); AgentRunner runner = new AgentRunner( new BusySpinIdleStrategy(), ex -> ex.printStackTrace(), null, agent); Executors.newSingleThreadExecutor().execute(runner); ``` -------------------------------- ### Get DirectBuffer ByteBuffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Retrieves the underlying ByteBuffer if the buffer is backed by one. Returns null if not. ```java ByteBuffer byteBuffer() ``` -------------------------------- ### Get absolute value of an integer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/BitUtil.md Returns the absolute value of an integer using a branchless implementation. ```java public static int abs(final int value) ``` -------------------------------- ### putBytes(int index, byte[] src, int offset, int length) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/MutableDirectBuffer.md Copies a specified portion of a byte array into the underlying buffer, starting at the given index and with a defined offset and length from the source array. ```APIDOC ## putBytes(int index, byte[] src, int offset, int length) ### Description Put an array of bytes into the underlying buffer with offset. ### Method void ### Parameters #### Path Parameters - **index** (int) - Required - Index in the underlying buffer to start from - **src** (byte[]) - Required - The byte array to copy - **offset** (int) - Required - Offset in the source buffer to begin the copy - **length** (int) - Required - Length of the source buffer to copy ``` -------------------------------- ### Handle Timer Expiry Exceptions in Agrona Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/errors.md Demonstrates how to safely handle exceptions thrown by a timer's expiry handler within Agrona's DeadlineTimerWheel. The example shows consuming the timer event even if an exception occurs to prevent retries. ```java wheel.poll( now, (timeUnit, currentTime, timerId) -> { try { processTimer(timerId); return true; // Consumed } catch (Exception e) { logger.error("Error processing timer {}: {}", timerId, e); return true; // Still consume to prevent retry } }, Integer.MAX_VALUE ); ``` -------------------------------- ### Get Maximum Message Length Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/RingBuffer.md Returns the maximum length allowed for a single message in bytes. ```java int maxMsgLength() ``` -------------------------------- ### getStringUtf8(int index) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Retrieves a length-prefixed String from UTF-8 encoded bytes starting at the specified index. ```APIDOC ## getStringUtf8(int index) ### Description Get a String from UTF-8 encoded bytes that is length prefixed. ### Method N/A (Java Method) ### Parameters #### Path Parameters - **index** (int) - Yes - Index at which the String begins ### Returns - **String** - The String as represented by UTF-8 encoded bytes. ``` -------------------------------- ### getStringAscii(int index) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Retrieves a length-prefixed String from ASCII encoded bytes starting at the specified index. ```APIDOC ## getStringAscii(int index) ### Description Get a String from ASCII encoded bytes that is length prefixed. ### Method N/A (Java Method) ### Parameters #### Path Parameters - **index** (int) - Yes - Index at which the String begins ### Returns - **String** - The String as represented by ASCII encoded bytes. ``` -------------------------------- ### byteBuffer() Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/UnsafeBuffer.md Gets the underlying ByteBuffer if the buffer is backed by one. Returns null if the buffer is not backed by a ByteBuffer. ```APIDOC ## byteBuffer() ### Description Gets the underlying ByteBuffer if the buffer is backed by one. Returns null if the buffer is not backed by a ByteBuffer. ### Method ```java public ByteBuffer byteBuffer() ``` ### Response #### Success Response (200) - **byteBuffer** (ByteBuffer) - The underlying ByteBuffer, or `null` if not backed by ByteBuffer. ``` -------------------------------- ### capacity() Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/UnsafeBuffer.md Gets the capacity of the buffer in bytes. This indicates the total size of the memory region managed by the UnsafeBuffer. ```APIDOC ## capacity() ### Description Gets the capacity of the buffer in bytes. This indicates the total size of the memory region managed by the UnsafeBuffer. ### Method ```java public int capacity() ``` ### Response #### Success Response (200) - **capacity** (int) - The current capacity in bytes. ``` -------------------------------- ### IntHashSet() Constructor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Creates a new IntHashSet with default configuration. The default initial capacity is 16 and the default load factor is 0.67. ```APIDOC ## IntHashSet() ### Description Creates a new IntHashSet with default configuration. ### Configuration - Initial capacity: 16 - Load factor: Hashing.DEFAULT_LOAD_FACTOR (0.67) ### Example ```java IntHashSet set = new IntHashSet(); ``` ``` -------------------------------- ### Get the number of entries in the map Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Returns the total count of key-value pairs currently stored in the map. ```java int count = map.size(); ``` -------------------------------- ### Building Collections Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/README.md Shows how to create and use Agrona's specialized hash maps and sets for efficient integer-based collections. ```java Int2ObjectHashMap map = new Int2ObjectHashMap<>(64, 0.75f); map.put(1, "Alice"); map.put(2, "Bob"); IntHashSet set = new IntHashSet(128); set.add(1); set.add(2); if (set.contains(1)) { System.out.println("Found"); } set.forEach(value -> System.out.println(value)); ``` -------------------------------- ### Get Native Memory Address Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/ExpandableDirectByteBuffer.md Retrieve the memory address of the underlying direct ByteBuffer using addressOffset(). ```java public long addressOffset() ``` -------------------------------- ### UnsafeBuffer Minimal Configuration Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Instantiate an UnsafeBuffer with default settings. ```java UnsafeBuffer buffer = new UnsafeBuffer(); ``` -------------------------------- ### Get Current Capacity Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/ExpandableDirectByteBuffer.md Retrieve the current allocated capacity of the buffer in bytes using the capacity() method. ```java public int capacity() ``` -------------------------------- ### Create IntHashSet with Initial Capacity and Load Factor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Create an IntHashSet with a specified initial capacity and load factor. Adjusting the load factor can balance memory usage and performance. A lower load factor reduces collisions but increases memory overhead. ```java public IntHashSet(int initialCapacity, float loadFactor) ``` ```java IntHashSet set = new IntHashSet(128, 0.75f); ``` -------------------------------- ### Java Hash Table Sizing with BitUtil Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/BitUtil.md Determine the appropriate capacity for hash tables by finding the next positive power of two using BitUtil.findNextPositivePowerOfTwo. Includes a check for power-of-two validation. ```java // Create hash table with power-of-2 capacity int requestedCapacity = 100; int actualCapacity = BitUtil.findNextPositivePowerOfTwo(requestedCapacity); // actualCapacity = 128 // Verify capacity is power of 2 if (BitUtil.isPowerOfTwo(actualCapacity)) { // Can use fast modulo: index = hash & (capacity - 1) } ``` -------------------------------- ### Java Memory Alignment with BitUtil Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/BitUtil.md Allocate buffers aligned to cache line boundaries using BitUtil.align. Also demonstrates accessing predefined constants for common structure sizes. ```java import org.agrona.BitUtil; // Allocate buffer aligned to cache line int size = 100; int alignedSize = BitUtil.align(size, BitUtil.CACHE_LINE_LENGTH); byte[] buffer = new byte[alignedSize]; // 128 bytes (cache-line aligned) // Structure sizes int structSize = BitUtil.SIZE_OF_INT + BitUtil.SIZE_OF_LONG + BitUtil.SIZE_OF_SHORT; ``` -------------------------------- ### Build Agrona JCStress Shadow Jar Source: https://github.com/aeron-io/agrona/blob/master/agrona-concurrency-tests/README.md Execute this Gradle command to build the JCStress binary. This step is required before running the tests directly. ```bash ./gradlew ./gradlew :agrona-concurrency-tests:shadowJar ``` -------------------------------- ### get(int key) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Retrieves the value associated with the specified key from the map. Returns null if the key is not found. ```APIDOC ## get(int key) ### Description Retrieves the value associated with the specified key from the map. Returns null if the key is not found. ### Method Signature V get(int key) ### Parameters #### Path Parameters - **key** (int) - Required - The key to look up ### Returns The value associated with the key, or `null` if the key is not present. ### Example ```java String value = map.get(1); ``` ``` -------------------------------- ### Timer Scheduling Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/README.md Shows how to schedule and process timers using Agrona's DeadlineTimerWheel for time-based events. ```java DeadlineTimerWheel wheel = new DeadlineTimerWheel( TimeUnit.MILLISECONDS, System.currentTimeMillis(), 1, // 1ms ticks 10000 // 10 second range ); long deadline = System.currentTimeMillis() + 5000; wheel.schedule(deadline, timerId); int expired = wheel.poll( System.currentTimeMillis(), (unit, now, id) -> { processExpiredTimer(id); return true; // Consume }, 100 // Max per poll ); ``` -------------------------------- ### Get Underlying AtomicBuffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/RingBuffer.md Retrieves the AtomicBuffer for direct read/write access. Use in conjunction with tryClaim() for zero-copy writes. ```java AtomicBuffer buffer() ``` -------------------------------- ### Select Agrona Idle Strategy Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Choose an IdleStrategy based on latency and CPU usage requirements. Options include BusySpin, Yielding, Sleeping, Backoff, and NoOp. ```java import org.agrona.concurrent.*; // Busy spin - lowest latency, highest CPU IdleStrategy strategy = new BusySpinIdleStrategy(); ``` ```java // Yielding - medium latency, medium CPU IdleStrategy strategy = new YieldingIdleStrategy(); ``` ```java // Sleeping - lowest CPU, medium latency IdleStrategy strategy = new SleepingIdleStrategy(); ``` ```java // Backoff - progressive backoff IdleStrategy strategy = new BackoffIdleStrategy( 64, // initial spins 128, // max spins 1, // min park nanos TimeUnit.MILLISECONDS.toNanos(1) // max park nanos ); ``` ```java // No idle - never idle IdleStrategy strategy = new NoOpIdleStrategy(); ``` -------------------------------- ### Get Char Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads a char value from the buffer at the specified byte offset. Use this for default byte order. ```Java char getChar(int index) ``` -------------------------------- ### Reading and Writing Buffers Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/README.md Demonstrates creating a mutable buffer and performing read/write operations for primitive types and strings. ```java MutableDirectBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(1024)); buffer.putInt(0, 42); buffer.putLong(4, System.currentTimeMillis()); buffer.putStringAscii(12, "Hello"); int value = buffer.getInt(0); long time = buffer.getLong(4); String text = buffer.getStringAscii(12); ``` -------------------------------- ### Get Short Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads a short value from the buffer at the specified byte offset. Use this for default byte order. ```Java short getShort(int index) ``` -------------------------------- ### Create IntHashSet with Initial Capacity Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Create an IntHashSet with a specified initial capacity. The capacity will be rounded up to the nearest power of 2. This is useful for pre-allocating space when the approximate number of elements is known. ```java public IntHashSet(int initialCapacity) ``` ```java IntHashSet set = new IntHashSet(64); ``` -------------------------------- ### Get Float Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads a float value from the buffer at the specified byte offset. Use this for default byte order. ```Java float getFloat(int index) ``` -------------------------------- ### AgentRunner Configuration Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Instantiate an AgentRunner with an IdleStrategy, ErrorHandler, and the Agent to run. ```java Agent agent = new MyAgent(); AgentRunner runner = new AgentRunner( idleStrategy, errorHandler, null, agent ); // Run on dedicated thread Executors.newSingleThreadExecutor().execute(runner); ``` -------------------------------- ### Get Double Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads a double value from the buffer at the specified byte offset. Use this for default byte order. ```Java double getDouble(int index) ``` -------------------------------- ### IntHashSet Default Configuration Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Instantiate an IntHashSet with default capacity (16) and load factor (0.67). ```java IntHashSet set = new IntHashSet(); ``` -------------------------------- ### Get Int Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads an int value from the buffer at the specified byte offset. Use this for default byte order. ```Java int getInt(int index) ``` -------------------------------- ### Get Long Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads a long value from the buffer at the specified byte offset. Use this for default byte order. ```Java long getLong(int index) ``` -------------------------------- ### Iterate Over Keys Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Demonstrates iterating through the keys of the map using the keySet() view. ```java for (int key : map.keySet()) { System.out.println(key); } ``` -------------------------------- ### IntHashSet(int initialCapacity) Constructor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Creates a new IntHashSet with a specified initial capacity. The capacity will be rounded up to the nearest power of 2. ```APIDOC ## IntHashSet(int initialCapacity) ### Description Creates a new IntHashSet with the specified initial capacity. ### Parameters #### Path Parameters - **initialCapacity** (int) - Required - Initial capacity (rounded to power of 2) ### Example ```java IntHashSet set = new IntHashSet(64); ``` ``` -------------------------------- ### Get the value associated with a key Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Retrieves the value associated with a given key. Returns null if the key is not present in the map. ```java String value = map.get(1); ``` -------------------------------- ### DeadlineTimerWheel Configuration Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Create a DeadlineTimerWheel with specified time unit, current time, tick resolution, and number of ticks. ```java DeadlineTimerWheel wheel = new DeadlineTimerWheel( TimeUnit.MILLISECONDS, System.currentTimeMillis(), 1, 1024 ); ``` -------------------------------- ### IntHashSet(IntHashSet setToCopy) Constructor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Creates a new IntHashSet by copying an existing IntHashSet. This is a deep copy. ```APIDOC ## IntHashSet(IntHashSet setToCopy) ### Description Creates a new IntHashSet by copying an existing IntHashSet. ### Parameters #### Path Parameters - **setToCopy** (IntHashSet) - Required - The set to copy ### Example ```java IntHashSet original = new IntHashSet(); original.add(1); original.add(2); IntHashSet copy = new IntHashSet(original); ``` ``` -------------------------------- ### getStringUtf8(int index, int length) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Retrieves a specified length of a String from UTF-8 encoded bytes starting at the given index. ```APIDOC ## getStringUtf8(int index, int length) ### Description Get part of a String from UTF-8 encoded bytes. ### Method N/A (Java Method) ### Parameters #### Path Parameters - **index** (int) - Yes - Index at which the String begins - **length** (int) - Yes - Length of the String in bytes to decode ### Returns - **String** - The String as represented by UTF-8 encoded bytes. ``` -------------------------------- ### UnsafeBuffer with Backing ByteBuffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Configure an UnsafeBuffer using a direct ByteBuffer. ```java UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(4096)); ``` -------------------------------- ### getStringAscii(int index, int length) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Retrieves a specified length of a String from ASCII encoded bytes starting at the given index. ```APIDOC ## getStringAscii(int index, int length) ### Description Get part of a String from ASCII encoded bytes. ### Method N/A (Java Method) ### Parameters #### Path Parameters - **index** (int) - Yes - Index at which the String begins - **length** (int) - Yes - Length of the String in bytes to decode ### Returns - **String** - The String as represented by ASCII encoded bytes. ``` -------------------------------- ### Agrona File Header Source: https://github.com/aeron-io/agrona/blob/master/CONTRIBUTING.md Include this header at the top of all new files to comply with the project's licensing and copyright requirements. ```java /* * Copyright 2014-2025 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ``` -------------------------------- ### Get Timer Count Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DeadlineTimerWheel.md Retrieves the number of currently active timers within the wheel. Use this to monitor the load on the timer wheel. ```java long timerCount() ``` -------------------------------- ### Get Iterator for IntHashSet Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Retrieves an iterator for traversing the elements within the IntHashSet. Use this to manually iterate through the set's values. ```java public IntIterator iterator() ``` ```java IntIterator iter = set.iterator(); while (iter.hasNext()) { int value = iter.nextValue(); System.out.println(value); } ``` -------------------------------- ### Get Key Set View Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Retrieves a set view of all keys present in the map. This view reflects changes made to the map. ```java KeySet keySet() ``` -------------------------------- ### IntHashSet(int initialCapacity, float loadFactor) Constructor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Creates a new IntHashSet with a specified initial capacity and load factor. The load factor determines when the set will resize. ```APIDOC ## IntHashSet(int initialCapacity, float loadFactor) ### Description Creates a new IntHashSet with the specified initial capacity and load factor. ### Parameters #### Path Parameters - **initialCapacity** (int) - Required - Initial capacity - **loadFactor** (float) - Required - Load factor for resizing (typically 0.5-0.9) ### Example ```java IntHashSet set = new IntHashSet(128, 0.75f); ``` ``` -------------------------------- ### Get the size of IntHashSet Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Retrieves the number of distinct values currently stored in the set. Use this to know how many elements are in the set. ```java int count = set.size(); System.out.println("Set contains " + count + " values"); ``` -------------------------------- ### Iterate Over Entries Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Demonstrates iterating through the entries of the map using the entrySet() view. ```java for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } ``` -------------------------------- ### DeadlineTimerWheel Constructor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DeadlineTimerWheel.md Creates a DeadlineTimerWheel with specified configuration, including time unit, current time, tick resolution, and the number of ticks per wheel. ```APIDOC ## Constructor DeadlineTimerWheel(TimeUnit timeUnit, long now, int tickResolution, int ticksPerWheel) ### Description Creates a DeadlineTimerWheel with specified configuration. ### Parameters #### Path Parameters - **timeUnit** (TimeUnit) - Required - Unit for deadline/now parameters (MILLISECONDS, MICROSECONDS, NANOSECONDS) - **now** (long) - Required - Current time in the specified timeUnit - **tickResolution** (int) - Required - Resolution of each tick in the timeUnit - **ticksPerWheel** (int) - Required - Number of ticks in the wheel (should be power of 2 for efficiency) ### Request Example ```java // Create wheel with 1ms tick resolution and 1000 ticks (1 second coverage) DeadlineTimerWheel wheel = new DeadlineTimerWheel( TimeUnit.MILLISECONDS, System.currentTimeMillis(), 1, // 1ms per tick 1024 // 1024 ticks ); ``` ``` -------------------------------- ### Write Operations with Automatic Expansion Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/ExpandableDirectByteBuffer.md Demonstrates how write operations on an ExpandableDirectByteBuffer automatically increase capacity when needed. Initialize the buffer with an initial capacity and perform various put operations. ```java ExpandableDirectByteBuffer buffer = new ExpandableDirectByteBuffer(128); // These operations will expand the buffer if necessary buffer.putInt(0, 42); buffer.putLong(4, 1234567890L); buffer.putStringAscii(12, "Hello World"); // Current capacity will be automatically increased to accommodate writes buffer.putBytes(100, largeDataArray); ``` -------------------------------- ### Int2ObjectHashMap() Constructor Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Creates a new Int2ObjectHashMap with default configuration, including a minimum initial capacity and default load factor. Iterator caching is enabled by default. ```APIDOC ## Int2ObjectHashMap() ### Description Creates a new Int2ObjectHashMap with default configuration. ### Method Constructor ### Parameters None ### Configuration - Initial capacity: MIN_CAPACITY (8) - Load factor: Hashing.DEFAULT_LOAD_FACTOR (0.67) - Iterator caching: enabled ### Example ```java Int2ObjectHashMap map = new Int2ObjectHashMap<>(); ``` ``` -------------------------------- ### Get Entry Set View Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Retrieves a set view of all entries (key-value pairs) in the map. This view reflects changes made to the map. ```java Set> entrySet() ``` -------------------------------- ### Message Protocol Encoding and Decoding with UnsafeBuffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/UnsafeBuffer.md Shows how to encode and decode messages using UnsafeBuffer, including header and payload management. Ensure the buffer has sufficient capacity before encoding. ```java import org.agrona.concurrent.UnsafeBuffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class MessageProtocol { // Message format: [type:4][length:4][payload:N] private static final int MSG_TYPE_OFFSET = 0; private static final int MSG_LENGTH_OFFSET = 4; private static final int MSG_PAYLOAD_OFFSET = 8; public static int encodeMessage( UnsafeBuffer buffer, int type, byte[] payload) { int messageLength = MSG_PAYLOAD_OFFSET + payload.length; // Check capacity if (messageLength > buffer.capacity()) { throw new IllegalArgumentException("Message too large"); } // Write header buffer.putInt(MSG_TYPE_OFFSET, type); buffer.putInt(MSG_LENGTH_OFFSET, messageLength); // Write payload buffer.putBytes(MSG_PAYLOAD_OFFSET, payload); return messageLength; } public static void decodeMessage( UnsafeBuffer buffer, int offset) { int type = buffer.getInt(offset + MSG_TYPE_OFFSET); int length = buffer.getInt(offset + MSG_LENGTH_OFFSET); byte[] payload = new byte[length - MSG_PAYLOAD_OFFSET]; buffer.getBytes(offset + MSG_PAYLOAD_OFFSET, payload); processMessage(type, payload); } } ``` -------------------------------- ### Get Values Collection View Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Retrieves a collection view of all values contained within the map. This view reflects changes made to the map. ```java Collection values() ``` -------------------------------- ### Get the internal capacity of IntHashSet Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/IntHashSet.md Retrieves the current allocated capacity of the internal arrays used by the set. This is distinct from the number of elements (size). ```java int capacity = set.capacity(); ``` -------------------------------- ### Int2ObjectHashMap Basic Usage Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/Int2ObjectHashMap.md Demonstrates the creation, population, retrieval, update, and removal of elements in an Int2ObjectHashMap. Includes efficient iteration without allocation. ```java import org.agrona.collections.Int2ObjectHashMap; // Create a map for user IDs to user objects Int2ObjectHashMap userMap = new Int2ObjectHashMap<>(64, 0.75f); // Add users userMap.put(1, new User("Alice")); userMap.put(2, new User("Bob")); userMap.put(3, new User("Charlie")); // Retrieve a user User user = userMap.get(1); System.out.println(user.getName()); // "Alice" // Check if user exists if (userMap.containsKey(2)) { System.out.println("User 2 exists"); } // Update a value User oldUser = userMap.put(1, new User("Alicia")); System.out.println(oldUser.getName()); // "Alice" // Remove a user userMap.remove(3); // Iterate efficiently without allocation userMap.forEach((userId, user) -> { System.out.println(userId + ": " + user.getName()); }); // Get size int count = userMap.size(); System.out.println("Total users: " + count); // Clear all userMap.clear(); ``` -------------------------------- ### Run JCStress Test Directly Source: https://github.com/aeron-io/agrona/blob/master/agrona-concurrency-tests/README.md Execute the built JCStress binary with your specified test and JVM arguments. Replace `YourTest` with the actual test class name. ```bash java -jar agrona-concurrency-tests/build/libs/concurrency-tests.jar YourTest -jvmArgsPrepend "--add-exports java.base/jdk.internal.misc=ALL-UNNAMED" ``` -------------------------------- ### putBytes(int index, ByteBuffer srcBuffer, int length) Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/MutableDirectBuffer.md Copies a specified number of bytes from a ByteBuffer, starting at its current position, into the underlying buffer. ```APIDOC ## putBytes(int index, ByteBuffer srcBuffer, int length) ### Description Put bytes from a ByteBuffer starting at its current position. ### Method void ### Parameters #### Path Parameters - **index** (int) - Required - Index in the underlying buffer to start from - **srcBuffer** (ByteBuffer) - Required - The ByteBuffer to copy bytes from - **length** (int) - Required - Length of the buffer to copy **Note**: The source buffer's position() will be advanced as a result. ``` -------------------------------- ### Instantiate OneToOneRingBuffer Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/RingBuffer.md Creates a RingBuffer optimized for a single producer and single consumer. It offers low overhead and latency without internal synchronization. ```java RingBuffer ringBuffer = new OneToOneRingBuffer( new UnsafeBuffer(ByteBuffer.allocateDirect(1024))); ``` -------------------------------- ### Get Byte Value Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/DirectBuffer.md Reads a byte value from the buffer at the specified byte offset. This method does not support specifying byte order as a byte has no inherent order. ```Java byte getByte(int index) ``` -------------------------------- ### UnsafeBuffer with Backing Byte Array Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/configuration.md Configure an UnsafeBuffer using a pre-allocated byte array. ```java UnsafeBuffer buffer = new UnsafeBuffer(new byte[1024]); ``` -------------------------------- ### Access Underlying Byte Array Source: https://github.com/aeron-io/agrona/blob/master/_autodocs/api-reference/ExpandableDirectByteBuffer.md Attempt to get the backing byte array using byteArray(). This method returns null as ExpandableDirectByteBuffer is not backed by a byte array. ```java public byte[] byteArray() ```