Class MpscRingBuffer<E>

java.lang.Object
express.mvp.roray.utils.concurrent.MpscRingBuffer<E>
Type Parameters:
E - the type of elements held in this buffer
All Implemented Interfaces:
AutoCloseable

public final class MpscRingBuffer<E> extends Object implements AutoCloseable
A high-performance, lock-free, off-heap friendly Multi-Producer Single-Consumer (MPSC) ring buffer.

Design Principles:

  • FFM-First: Uses MemorySegment and VarHandle for safe, efficient memory access.
  • Zero-Allocation: No objects allocated during offer(Object) or poll().
  • False Sharing Protection: Critical fields (producer/consumer indices) are padded to separate cache lines.
  • Mechanical Sympathy: Optimized for modern CPU architectures with relaxed consistency models.

This implementation is inspired by JCTools' MpscArrayQueue but built natively on Java 21+ FFM.

  • Constructor Details

    • MpscRingBuffer

      public MpscRingBuffer(int capacity)
      Creates a new MpscRingBuffer.
      Parameters:
      capacity - the capacity of the buffer (must be a power of 2)
  • Method Details

    • offer

      public boolean offer(E e)
      Offers an element to the queue.

      This method is thread-safe for multiple producers.

      Parameters:
      e - the element to offer (must not be null)
      Returns:
      true if successful, false if the queue is full
    • poll

      public E poll()
      Polls an element from the queue.

      This method is NOT thread-safe and must be called by a single consumer.

      Returns:
      the element, or null if empty
    • isEmpty

      public boolean isEmpty()
      Checks if the queue is empty.
      Returns:
      true if the queue is empty, false otherwise
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable