### Build and Package Disruptor Source: https://github.com/conversant/disruptor/blob/master/README.md Run this command to build and package the Disruptor library using Maven. Ensure you have Maven installed. ```bash mvn -U clean package ``` -------------------------------- ### Configuration Updates Example Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/SequenceLock.md Illustrates updating configuration settings using SequenceLock. The `updateSettings` method uses a timed write lock acquisition to prevent indefinite blocking. ```java class Configuration { private String[] settings = new String[100]; private OptimisticLock lock = new SequenceLock(); public String getSetting(int index) { String result; long token; do { token = lock.readLock(); result = settings[index]; } while (!lock.readLockHeld(token)); return result; } public void updateSettings(String[] newSettings) { long token; try { token = lock.tryWriteLock(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } if (token > 0) { try { System.arraycopy(newSettings, 0, settings, 0, newSettings.length); } finally { lock.unlock(token); } } } } ``` -------------------------------- ### Time Unit Examples for Blocking Operations Source: https://github.com/conversant/disruptor/blob/master/_autodocs/types.md Demonstrates the usage of various java.util.concurrent.TimeUnit constants for specifying timeouts in blocking operations. ```java queue.offer(element, 100, TimeUnit.MILLISECONDS); // 100ms timeout queue.poll(5, TimeUnit.SECONDS); // 5 second timeout stack.push(item, 1, TimeUnit.MICROSECONDS); // 1 microsecond timeout ``` -------------------------------- ### Performance Tuning with SpinPolicy Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Examples demonstrating the performance characteristics of different SpinPolicy settings for DisruptorBlockingQueue. Choose based on latency and CPU usage requirements. ```java // Ultra-low latency: SPINNING DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(4096, SpinPolicy.SPINNING); // Typical latency: 3-5 ns per transfer // CPU usage: 100% of waiting thread // Balanced: WAITING (default) DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(4096); // Typical latency: 50-100 ns per transfer // CPU usage: 20-50% of waiting thread // CPU-friendly: BLOCKING DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(4096, SpinPolicy.BLOCKING); // Typical latency: 1-10 microseconds per transfer // CPU usage: Near 0% during waits ``` -------------------------------- ### Producer-Consumer Example with ConcurrentStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentStack.md Demonstrates a typical producer-consumer pattern using ConcurrentStack. The producer pushes tasks onto the stack, and the consumer pops and processes them. Uses interruptible push and pop operations. ```java ConcurrentStack stack = new ConcurrentStack<>(512, SpinPolicy.WAITING); // Producer thread Thread producer = new Thread(() -> { for (int i = 0; i < 1000; i++) { try { stack.pushInterruptibly("task-" + i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } }); // Consumer thread Thread consumer = new Thread(() -> { try { while (true) { String task = stack.popInterruptibly(); System.out.println("Processing: " + task); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); producer.start(); consumer.start(); ``` -------------------------------- ### Migration from java.util.Stack to FixedStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Provides code examples for migrating from the thread-safe but less performant java.util.Stack to FixedStack for single-threaded scenarios or ConcurrentStack for multi-threaded scenarios. ```java // Old code Stack stack = new Stack<>(); stack.push("value"); String value = stack.pop(); // New code (if single-threaded) FixedStack stack = new FixedStack<>(256); stack.push("value"); String value = stack.pop(); // New code (if multi-threaded) ConcurrentStack stack = new ConcurrentStack<>(256); try { stack.pushInterruptibly("value"); String value = stack.popInterruptibly(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ``` -------------------------------- ### Intra-thread Messaging Example Source: https://github.com/conversant/disruptor/wiki/Home This Java example demonstrates a contrived scenario for performing calculations in a separate thread using a BlockingQueue and AtomicSequence for synchronization. It's suitable for lower-performing asynchronous operations. ```Java package com.conversant.util.concurrent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Created by jcairns on 12/30/15. */ public class DisruptorExample { private final BlockingQueue messageQueue; private final ExecutorService calcThreads; private volatile boolean isStopped = false; private final AtomicSequence accumulatorSequence = new AtomicSequence(); private volatile int accumulator = -1; DisruptorExample() { messageQueue = new DisruptorBlockingQueue<>(512); final int nThreads = Runtime.getRuntime().availableProcessors(); calcThreads = Executors.newFixedThreadPool(nThreads); for(int i=0; i 0) { try { value = newValue; } finally { lock.unlock(token); } } } } ``` -------------------------------- ### Create a new SequenceLock Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/SequenceLock.md Initializes a new SequenceLock. The lock starts in an unlocked state with an even sequence number (2). ```java public SequenceLock() ``` ```java OptimisticLock lock = new SequenceLock(); ``` -------------------------------- ### Build Package, Source, and Jar Source: https://github.com/conversant/disruptor/wiki/Sonatype-Release-Process Use this command to clean, build, and package the project artifacts including source and javadoc jars. ```bash mvn -U clean source:jar javadoc:jar compile test verify package ``` -------------------------------- ### iterator() Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Returns an iterator over the elements in the queue, starting from the head of the queue. ```APIDOC ## iterator() ### Description Returns an iterator over the queue elements. ### Method `iterator()` ### Returns - `Iterator` - iterator starting at queue head ``` -------------------------------- ### Get Capacity of PushPullBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Returns the maximum capacity of the queue. The capacity is a fixed power of 2. ```java public int capacity() ``` ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(100); System.out.println(queue.capacity()); // 128 (next power of 2) ``` -------------------------------- ### Depth-First Search using Stack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/Stack.md Illustrates how to implement Depth-First Search (DFS) using a stack to manage nodes to visit. ```java Stack nodeStack = new FixedStack<>(1000); nodeStack.push(root); while (!nodeStack.isEmpty()) { Node current = nodeStack.pop(); process(current); if (current.hasLeftChild()) { nodeStack.push(current.getLeftChild()); } if (current.hasRightChild()) { nodeStack.push(current.getRightChild()); } } ``` -------------------------------- ### Instantiating Generic Collections Source: https://github.com/conversant/disruptor/blob/master/_autodocs/types.md Demonstrates how to instantiate generic collections like DisruptorBlockingQueue and ConcurrentStack with specific element types. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); ConcurrentStack stack = new ConcurrentStack<>(256); ``` -------------------------------- ### Convert DisruptorBlockingQueue to an Object array Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Use toArray() to get an array representation of all elements currently in the queue. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); queue.offer("a"); queue.offer("b"); Object[] arr = queue.toArray(); ``` -------------------------------- ### Get Current Size of ConcurrentStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentStack.md Returns the number of elements currently present in the stack. This is a non-blocking operation. ```java public int size() ``` ```java ConcurrentStack stack = new ConcurrentStack<>(256); stack.push("a"); stack.push("b"); System.out.println(stack.size()); // 2 ``` -------------------------------- ### Correct Usage of ConcurrentQueue Size vs Offer Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentQueue.md Demonstrates the correct pattern for handling queue capacity by checking the return value of offer() or remainingCapacity() instead of relying on size() for synchronization, which can be inaccurate in concurrent environments. ```java // Wrong: Size-based synchronization if (queue.size() < queue.capacity()) { queue.offer(item); // May fail if another thread fills queue } // Right: Check return value if (!queue.offer(item)) { // Queue full } // Right: Check remaining capacity if (queue.remainingCapacity() > 0) { queue.offer(item); } ``` -------------------------------- ### Get ConcurrentQueue Capacity Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentQueue.md Retrieves the fixed maximum capacity of the queue. The capacity is always a power of 2 and is set at construction. ```java int capacity() ``` ```java ConcurrentQueue queue = new PushPullConcurrentQueue<>(1000); System.out.println(queue.capacity()); // 1024 (rounded to next power of 2) ``` -------------------------------- ### Create Release Bundle JAR Source: https://github.com/conversant/disruptor/wiki/Sonatype-Release-Process Create the final bundle JAR file containing all release artifacts for upload to Sonatype. ```bash jar -cvf disruptor-1.0.0-bundle.jar disruptor-1.0.0* ``` -------------------------------- ### Producer-Consumer Pattern with DisruptorBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/README.md Demonstrates the basic Producer-Consumer pattern using DisruptorBlockingQueue. Producers add tasks, and consumers retrieve and execute them. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); // Producer thread queue.put(new Task()); // Consumer thread Task task = queue.take(); task.execute(); ``` -------------------------------- ### Get Remaining Capacity of ConcurrentStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentStack.md Returns the number of additional elements that can be added to the stack before it becomes full. This is a non-blocking operation. ```java public int remainingCapacity() ``` ```java ConcurrentStack stack = new ConcurrentStack<>(256); System.out.println(stack.remainingCapacity()); // 256 stack.push("x"); System.out.println(stack.remainingCapacity()); // 255 ``` -------------------------------- ### Sign Bundle Files with GPG Source: https://github.com/conversant/disruptor/wiki/Sonatype-Release-Process Sign all bundle files (pom, source jar, doc jar, dist jar) using a publicly hosted GPG key. ```bash for i in disruptor-1.0.1*; do gpg -ab $i; done ``` -------------------------------- ### Get Current Size of FixedStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Retrieves the current number of elements present in the stack. This is a simple count of items currently stored. ```java public int size() ``` ```java FixedStack stack = new FixedStack<>(256); stack.push("a"); stack.push("b"); System.out.println(stack.size()); // 2 ``` -------------------------------- ### Initialize DisruptorBlockingQueue with Collection Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Demonstrates initializing a DisruptorBlockingQueue with a pre-populated collection of elements. The elements are added in the iteration order of the provided collection. ```java List initial = Arrays.asList("a", "b", "c"); new DisruptorBlockingQueue<>(1024, initial); ``` ```java List initial = Arrays.asList("a", "b", "c"); new PushPullBlockingQueue<>(512, initial); ``` ```java List initial = Arrays.asList("a", "b", "c"); new MPMCBlockingQueue<>(2048, initial); ``` ```java // Initialize with values List messages = Arrays.asList("msg1", "msg2", "msg3"); DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024, messages); // Verify initialization System.out.println(queue.size()); // 3 System.out.println(queue.peek()); // "msg1" ``` ```java // Initialize with both values and spin policy List initial = Arrays.asList("ready", "set", "go"); DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(256, SpinPolicy.SPINNING); for (String s : initial) { queue.offer(s); } ``` -------------------------------- ### Get Remaining Capacity in Java Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Returns the number of additional elements the queue can accept without blocking. Useful for monitoring queue fullness. ```java public int remainingCapacity() ``` ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); queue.offer("msg"); System.out.println(queue.remainingCapacity()); // 1023 ``` -------------------------------- ### Expression Evaluation using Stacks Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/Stack.md Demonstrates evaluating expressions, specifically postfix notation, using separate stacks for values and operators. ```java Stack valueStack = new FixedStack<>(50); Stack operatorStack = new FixedStack<>(50); // Evaluate postfix expression void evaluatePostfix(String expr) { String[] tokens = expr.split(" "); for (String token : tokens) { if (isNumber(token)) { valueStack.push(Double.parseDouble(token)); } else if (isOperator(token)) { double b = valueStack.pop(); double a = valueStack.pop(); double result = apply(token, a, b); valueStack.push(result); } } if (!valueStack.isEmpty()) { System.out.println(valueStack.pop()); } } ``` -------------------------------- ### Get Approximate Queue Size Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Retrieves the approximate number of elements currently in the queue. Note that this value can be inconsistent in highly concurrent environments. ```java public int size() ``` ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); queue.offer("msg1"); queue.offer("msg2"); System.out.println(queue.size()); // approximately 2 ``` -------------------------------- ### Using SpinPolicy.WAITING instead of SPINNING Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Shows how to switch from the potentially high-CPU `SpinPolicy.SPINNING` to the default `SpinPolicy.WAITING` to reduce CPU usage when not strictly necessary. ```java // Instead of //new DisruptorBlockingQueue<>(1024, SpinPolicy.SPINNING); // Use new DisruptorBlockingQueue<>(1024, SpinPolicy.WAITING); ``` -------------------------------- ### Get Remaining Capacity of PushPullBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Returns the number of additional elements the queue can accept without blocking. Useful for understanding current queue capacity. ```java public int remainingCapacity() ``` ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(256); System.out.println(queue.remainingCapacity()); // 256 queue.offer("x"); System.out.println(queue.remainingCapacity()); // 255 ``` -------------------------------- ### Best Practice: Pre-allocate with Margin Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Allocate the FixedStack with a capacity larger than the expected number of items to accommodate potential growth and avoid overflow. ```java // If you expect 1000 items, allocate extra FixedStack stack = new FixedStack<>(2048); ``` -------------------------------- ### Get Approximate Size of PushPullBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Retrieves the approximate number of elements currently in the queue. Note that this value can change immediately after retrieval in concurrent environments. ```java public int size() ``` ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(256); queue.offer(1); queue.offer(2); System.out.println(queue.size()); // approximately 2 ``` -------------------------------- ### Stack Iteration (LIFO) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/Stack.md Demonstrates processing elements from a stack in Last-In, First-Out (LIFO) order. ```java Stack stack = new FixedStack<>(256); // Populate stack... // Process in LIFO order while (!stack.isEmpty()) { Item item = stack.pop(); process(item); } ``` -------------------------------- ### Using put() instead of offer() for Blocking Offers Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Illustrates the correct way to handle a full queue by using the blocking `put()` operation instead of a non-blocking `offer()` that might discard items. ```java // Instead of //if (!queue.offer(item)) { // // discard item // WRONG //} // Do this try { queue.put(item); // Wait for space } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ``` -------------------------------- ### Get the number of available slots Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/Stack.md Returns the number of additional elements the stack can accept. This is an O(1) operation with nanosecond latency and is equivalent to capacity() - size(). ```java int remainingCapacity() ``` ```java Stack stack = new FixedStack<>(256); System.out.println(stack.remainingCapacity()); // 256 stack.push("x"); System.out.println(stack.remainingCapacity()); // 255 ``` ```java if (stack.remainingCapacity() > 0) { stack.push(element); } ``` -------------------------------- ### Get the total capacity of the stack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/Stack.md Returns the total capacity of the stack. This method is specific to implementations like FixedStack and is not part of the base Stack interface. ```java Stack stack = new FixedStack<>(1000); // Capacity will be 1024 (next power of 2) ``` -------------------------------- ### Initialize Disruptor Stacks with Capacity Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Instantiate various Disruptor stack types with a specified capacity. The capacity is rounded up to the next power of 2. ```java new ConcurrentStack<>(256); new FixedStack<>(512); ``` -------------------------------- ### Get Queue Capacity Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Returns the maximum capacity configured for the queue. The actual internal capacity will be the next power of 2 greater than or equal to the specified capacity. ```java public int capacity() ``` ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1000); System.out.println(queue.capacity()); // 1024 (next power of 2) ``` -------------------------------- ### Configure PushPullBlockingQueue for Embedded Systems Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Sets up a PushPullBlockingQueue for embedded systems with a small capacity and the CPU-friendly BLOCKING spin policy. This is optimized for single-producer, single-consumer scenarios. ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>( 256, // Small capacity SpinPolicy.BLOCKING // CPU-friendly ); ``` -------------------------------- ### Get the current number of elements Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/Stack.md Returns the current number of elements on the stack. This is an O(1) operation with nanosecond latency. In concurrent scenarios, the size may be approximate. ```java int size() ``` ```java Stack stack = new FixedStack<>(256); stack.push("a"); stack.push("b"); System.out.println(stack.size()); // 2 ``` -------------------------------- ### offer(E e) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Attempts to insert an element into the queue, returning immediately with success or failure. Returns true if the element was added, false if the queue is full. ```APIDOC ## offer(E e) ### Description Attempts to insert an element into the queue, returning immediately with success or failure. ### Parameters #### Path Parameters - **e** (E) - Required - Element to add to the queue ### Returns - **boolean** - true if the element was added, false if the queue is full ### Request Example ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); if (queue.offer("message")) { System.out.println("Added successfully"); } else { System.out.println("Queue full"); } ``` ``` -------------------------------- ### Create Hard Link for JDK8 Build Source: https://github.com/conversant/disruptor/wiki/Sonatype-Release-Process If building with JDK8, create a hard link to the 'main' JAR for Maven compatibility. ```bash ln -f disruptor-1.0.0-jdk8.jar disruptor-1.0.0.jar ``` -------------------------------- ### Create PushPullBlockingQueue with Capacity and Spin Policy Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Creates a new blocking queue with a specified capacity and spin policy. Choose the spin policy based on latency and CPU usage requirements. ```java public PushPullBlockingQueue(final int capacity, final SpinPolicy spinPolicy) ``` ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(512, SpinPolicy.SPINNING); ``` -------------------------------- ### Get Remaining Capacity of FixedStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Calculates and returns the number of additional elements that can be added to the stack before it becomes full. This is derived from the total capacity minus the current size. ```java public int remainingCapacity() ``` ```java FixedStack stack = new FixedStack<>(256); System.out.println(stack.remainingCapacity()); // 256 stack.push("x"); System.out.println(stack.remainingCapacity()); // 255 ``` -------------------------------- ### add(E e) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Adds an element to the queue, throwing an exception if the queue is full. This differs from `offer()` which returns false instead. ```APIDOC ## add(E e) ### Description Adds an element to the queue, throwing an exception if the queue is full. Differs from `offer()` which returns false instead. ### Parameters #### Path Parameters - e (E) - Required - Element to add ### Response #### Success Response (200) - boolean - always true (or throws exception) ### Throws - IllegalStateException - if queue is full ### Request Example ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(2); queue.add("msg1"); queue.add("msg2"); try { queue.add("msg3"); // throws } catch (IllegalStateException ise) { System.out.println("Queue full"); } ``` ``` -------------------------------- ### Create a FixedStack Instance Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Instantiates a FixedStack with a specified capacity. The capacity will be rounded up to the next power of 2 if the provided size is not already a power of 2. The capacity is fixed after construction. ```java public FixedStack(final int size) ``` ```java FixedStack stack = new FixedStack<>(256); ``` -------------------------------- ### Get Approximate Size of ConcurrentQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentQueue.md Returns the approximate current number of elements in the queue. This operation is O(1) and non-blocking but may be inaccurate in concurrent scenarios. Use it as a hint rather than for synchronization. ```java int size() ``` ```java ConcurrentQueue queue = new PushPullConcurrentQueue<>(1024); queue.offer("a"); queue.offer("b"); System.out.println(queue.size()); // approximately 2 ``` -------------------------------- ### Create ConcurrentStack with Custom Spin Policy Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentStack.md Instantiates a ConcurrentStack with a specified capacity and spin policy. Choose from WAITING, SPINNING, or BLOCKING based on performance and CPU usage needs. ```java public ConcurrentStack(final int size, final SpinPolicy spinPolicy) ``` ```java ConcurrentStack stack = new ConcurrentStack<>(512, SpinPolicy.SPINNING); ``` -------------------------------- ### Batch Processing with DisruptorBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Shows how to perform batch processing using DisruptorBlockingQueue. A consumer drains elements into a batch array and processes it when elements are available. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(10000); // Batch consumer String[] batch = new String[1000]; while (true) { int count = queue.drainTo(batch); if (count > 0) { processBatch(batch, count); } else { Thread.sleep(10); } } ``` -------------------------------- ### Convert DisruptorBlockingQueue to a typed array Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Use toArray(T[] a) to get an array representation of queue elements, using the provided array if large enough. A new array is allocated if the provided one is too small. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); queue.offer("msg1"); queue.offer("msg2"); String[] results = new String[2]; queue.toArray(results); // [msg1, msg2] ``` -------------------------------- ### Initialize Disruptor Queues with Capacity Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Instantiate various Disruptor queue types with a specified capacity. The capacity is rounded up to the next power of 2. ```java new DisruptorBlockingQueue<>(1024); new PushPullBlockingQueue<>(512); new MPMCBlockingQueue<>(2048); new MultithreadConcurrentQueue<>(1024); new PushPullConcurrentQueue<>(256); ``` -------------------------------- ### FixedStack vs. java.util.Stack Performance Benchmark Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Compares the push operation performance between FixedStack and java.util.Stack. FixedStack demonstrates significantly faster performance due to its optimized implementation. ```java // Benchmark comparison FixedStack fixedStack = new FixedStack<>(100000); java.util.Stack javaStack = new java.util.Stack<>(); // FixedStack: ~1-2 nanoseconds per push long start = System.nanoTime(); for (int i = 0; i < 100000; i++) { fixedStack.push(i); } long fixedTime = System.nanoTime() - start; // java.util.Stack: ~10-20 nanoseconds per push start = System.nanoTime(); for (int i = 0; i < 100000; i++) { javaStack.push(i); } long javaTime = System.nanoTime() - start; // FixedStack is 5-10x faster System.out.println("Speedup: " + (double)javaTime / fixedTime); ``` -------------------------------- ### Drain Queue to Batch Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Demonstrates using the drainTo method to efficiently process elements in batches. ```java String[] batch = new String[100]; int count = queue.drainTo(batch); for (int i = 0; i < count; i++) { processBatch[i]; } ``` -------------------------------- ### offer(E e) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Attempts to insert the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. Returns true if the element was added, false otherwise. ```APIDOC ## offer(E e) ### Description Attempts to insert an element without blocking. Returns true if the element was added successfully, or false if the queue is full. ### Method `offer` ### Parameters #### Path Parameters - **e** (E) - Required - Element to add ### Returns - **boolean** - true if the element was added to the queue, false otherwise. ### Request Example ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(256); if (queue.offer("data")) { System.out.println("Enqueued"); } else { System.out.println("Queue full - offer failed"); } ``` ``` -------------------------------- ### Producer-Consumer with Timeout Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/BlockingStack.md Demonstrates pushing items with a timeout and popping items with a timeout. Use when producers or consumers might need to wait for space or availability but should not block indefinitely. ```java BlockingStack stack = new ConcurrentStack<>(1024); // Producer boolean succeeded = stack.push(item, 5, TimeUnit.SECONDS); if (!succeeded) { log.warn("Failed to push item; stack full"); } // Consumer Item item = stack.pop(1, TimeUnit.SECONDS); if (item != null) { process(item); } else { log.debug("No items available"); } ``` -------------------------------- ### Copy and Rename POM File Source: https://github.com/conversant/disruptor/wiki/Sonatype-Release-Process Copy the project's POM file to the target directory, ensuring it adheres to Sonatype conventions. ```bash cp ../pom.xml disruptor-1.0.0.xml ``` -------------------------------- ### Single Producer, Single Consumer Queue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Demonstrates the basic usage of PushPullBlockingQueue for a single producer and single consumer scenario. ```java import com.conversantmedia.util.concurrent.PushPullBlockingQueue; PushPullBlockingQueue queue = new PushPullBlockingQueue<>(1024); // Producer queue.offer("message"); // Consumer String msg = queue.poll(); if (msg != null) { System.out.println("Got: " + msg); } ``` -------------------------------- ### Create ConcurrentStack with Default Spin Policy Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentStack.md Instantiates a ConcurrentStack with a specified capacity. The default spin policy (WAITING) is used. The capacity is rounded up to the next power of 2. ```java public ConcurrentStack(final int size) ``` ```java ConcurrentStack stack = new ConcurrentStack<>(256); ``` -------------------------------- ### Multi-Producer, Multi-Consumer Queue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Shows how to use DisruptorBlockingQueue for scenarios with multiple producers and multiple consumers. ```java import com.conversantmedia.util.concurrent.DisruptorBlockingQueue; import com.conversantmedia.util.concurrent.SpinPolicy; DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024, SpinPolicy.WAITING); // Producer thread if (queue.offer("task1")) { System.out.println("Queued"); } // Consumer thread String task = queue.poll(); if (task != null) { processTask(task); } ``` -------------------------------- ### Setting Capacity to Power of 2 Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Illustrates the performance benefit of setting queue capacity to a power of 2. ```java // Good: Next power of 2 is 1024 new DisruptorBlockingQueue<>(1000); // Better: Exact power of 2 new DisruptorBlockingQueue<>(1024); ``` -------------------------------- ### SequenceLock Writer State Transitions Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/SequenceLock.md Illustrates the state transitions for a writer acquiring and releasing a write lock. The sequence increments by one for each state change. ```text Even (read possible) → Inc by 1 → Odd (no reads start) → Modify → Inc by 1 → Even ``` -------------------------------- ### Create PushPullBlockingQueue from Collection Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Initializes a new blocking queue with a given capacity and populates it with elements from an existing collection. ```java public PushPullBlockingQueue(final int capacity, Collection c) ``` ```java List initial = Arrays.asList("alpha", "beta", "gamma"); PushPullBlockingQueue queue = new PushPullBlockingQueue<>(256, initial); ``` -------------------------------- ### Offer Element to PushPullBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Attempts to insert an element into the queue without blocking. Returns true if successful, false if the queue is full. ```java public boolean offer(E e) ``` ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(256); if (queue.offer("data")) { System.out.println("Enqueued"); } else { System.out.println("Queue full - offer failed"); } ``` -------------------------------- ### Configure DisruptorBlockingQueue for Ultra-Low Latency Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Sets up a DisruptorBlockingQueue for minimal latency by using a large capacity and the SPINNING policy. This configuration is suitable for high-frequency trading or real-time systems. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>( 4096, // Large capacity to minimize waits SpinPolicy.SPINNING // Continuous spinning ); ``` -------------------------------- ### Using take() for Blocking Polls Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Demonstrates how to use the blocking `take()` operation to wait for elements when polling from a queue, ensuring a non-null result when an element is available. ```java // Instead of //String item = queue.poll(); //if (item != null) { ... } // For blocking try { String item = queue.take(); // Wait for element // Always non-null here } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ``` -------------------------------- ### offer(E e) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentQueue.md Attempts to add an element to the queue without blocking. Returns true if successful, false if the queue is full. This operation is non-blocking and thread-safe for concurrent producers. ```APIDOC ## offer(E e) ### Description Attempts to add an element to the queue without blocking. Returns true if the element was successfully added, and false if the queue is full. This method is non-blocking and designed for concurrent producer safety. ### Method `boolean offer(E e)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **e** (E) - Required - Element to add ### Request Example ```java ConcurrentQueue queue = new PushPullConcurrentQueue<>(1024); if (queue.offer("data")) { System.out.println("Element added"); } else { System.out.println("Queue full - element rejected"); } ``` ### Response #### Success Response (true) Returns `true` if the element was successfully added to the queue. #### Error Response (false) Returns `false` if the queue is full and the element could not be added. #### Response Example `true` or `false` ``` -------------------------------- ### Verify GPG Signatures Source: https://github.com/conversant/disruptor/wiki/Sonatype-Release-Process Verify that all generated .asc signature files are correctly signed. ```bash for i in *.asc; do gpg --verify $i; done ``` -------------------------------- ### FixedStack Constructor Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Creates a new fixed-size stack with the given capacity. The capacity will be rounded up to the nearest power of 2 if the provided size is not a power of 2. The capacity is fixed after construction. ```APIDOC ## FixedStack(int size) ### Description Creates a new fixed-size stack with the given capacity. ### Parameters #### Path Parameters - **size** (int) - Required - Stack capacity; will be rounded up to next power of 2 ### Request Example ```java FixedStack stack = new FixedStack<>(256); ``` ``` -------------------------------- ### offer(E e, long timeout, TimeUnit unit) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Attempts to add an element to the queue, waiting up to the specified time if the queue is full. ```APIDOC ## offer(E e, long timeout, TimeUnit unit) ### Description Attempts to add an element to the queue, waiting up to the specified time if the queue is full. ### Method `public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **e** (E) - Required - Element to add * **timeout** (long) - Required - Maximum time to wait * **unit** (TimeUnit) - Required - Unit of the timeout parameter (NANOSECONDS, MILLISECONDS, etc.) ### Request Example ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(100); try { boolean added = queue.offer("msg", 5, TimeUnit.SECONDS); if (added) { System.out.println("Element added"); } else { System.out.println("Timeout - queue still full"); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } ``` ### Response #### Success Response (200) * **return value** (boolean) - true if element was added, false if timeout expired ### Throws * `InterruptedException` — if interrupted while waiting ``` -------------------------------- ### capacity() Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/ConcurrentQueue.md Returns the fixed maximum capacity of the queue. The capacity is always a power of 2 and is set at construction. ```APIDOC ## capacity() ### Description Returns the fixed maximum capacity of the queue. The capacity is always a power of 2 and is set at construction. ### Method ```java int capacity() ``` ### Returns `int` — the queue's fixed capacity (always a power of 2) ### Usage Example ```java ConcurrentQueue queue = new PushPullConcurrentQueue<>(1000); System.out.println(queue.capacity()); // 1024 (rounded to next power of 2) ``` ### Semantics - Capacity is fixed at construction and cannot change. - Always a power of 2. - Maximum possible value: 1,073,741,824 (2^30). ``` -------------------------------- ### Work Stealing Stack with ConcurrentStack Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Demonstrates setting up a work-stealing stack using ConcurrentStack for multiple worker threads. Workers continuously pop jobs, execute them, or yield if no work is available. ```java ConcurrentStack workStack = new ConcurrentStack<>(2048); // Multiple workers for (int i = 0; i < 4; i++) { new Thread(() -> { try { while (true) { Job job = workStack.pop(100, TimeUnit.MILLISECONDS); if (job != null) { job.execute(); } else { Thread.yield(); // No work; yield } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); } ``` -------------------------------- ### Create DisruptorBlockingQueue with Capacity Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Instantiates a DisruptorBlockingQueue with a specified capacity. The capacity will be rounded up to the next power of 2. ```java public DisruptorBlockingQueue(final int capacity) ``` ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024); ``` -------------------------------- ### Create DisruptorBlockingQueue with Capacity and Spin Policy Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Creates a DisruptorBlockingQueue with a given capacity and a spin policy to control thread waiting behavior. Choose WAITING for best performance, SPINNING for lower latency, or BLOCKING for standard Java synchronization. ```java public DisruptorBlockingQueue(final int capacity, final SpinPolicy spinPolicy) ``` ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>( 1024, SpinPolicy.SPINNING ); ``` -------------------------------- ### PushPullBlockingQueue Constructor (Capacity, SpinPolicy) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Creates a new blocking queue with the specified capacity and spin policy. The capacity will be rounded up to the next power of 2. ```APIDOC ## PushPullBlockingQueue(int capacity, SpinPolicy spinPolicy) ### Description Creates a new blocking queue with specified capacity and spin policy. ### Method Constructor ### Parameters #### Path Parameters - **capacity** (int) - Required - Initial queue capacity; rounded to next power of 2 - **spinPolicy** (SpinPolicy) - Required - Thread behavior: WAITING (default), BLOCKING, or SPINNING ### Request Example ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(512, SpinPolicy.SPINNING); ``` ``` -------------------------------- ### PushPullBlockingQueue Constructor (Capacity, Collection) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Creates a new blocking queue with the specified capacity and initializes it with elements from a given collection. ```APIDOC ## PushPullBlockingQueue(int capacity, Collection c) ### Description Creates a new blocking queue initialized with elements from a collection. ### Method Constructor ### Parameters #### Path Parameters - **capacity** (int) - Required - Initial queue capacity; rounded to next power of 2 - **c** (Collection) - Required - Collection whose elements populate the queue ### Request Example ```java List initial = Arrays.asList("alpha", "beta", "gamma"); PushPullBlockingQueue queue = new PushPullBlockingQueue<>(256, initial); ``` ``` -------------------------------- ### PushPullBlockingQueue Constructor (Capacity) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Creates a new blocking queue with the specified capacity. The capacity will be rounded up to the next power of 2. Uses the default WAITING spin policy. ```APIDOC ## PushPullBlockingQueue(int capacity) ### Description Creates a new blocking queue with the given capacity and default spin policy (WAITING). ### Method Constructor ### Parameters #### Path Parameters - **capacity** (int) - Required - Initial queue capacity; will be rounded up to the next power of 2 ### Request Example ```java PushPullBlockingQueue queue = new PushPullBlockingQueue<>(1024); ``` ``` -------------------------------- ### size() Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/FixedStack.md Returns the current number of elements on the stack. ```APIDOC ## size() ### Description Returns the current number of elements on the stack. ### Returns - **int** - number of elements currently in the stack ### Request Example ```java FixedStack stack = new FixedStack<>(256); stack.push("a"); stack.push("b"); System.out.println(stack.size()); // 2 ``` ``` -------------------------------- ### Blocking Operations with Timeouts Source: https://github.com/conversant/disruptor/blob/master/_autodocs/QUICK_START.md Illustrates how to use offer and poll with timeouts for blocking operations on DisruptorBlockingQueue. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(256); // Producer: Wait up to 5 seconds for space try { boolean added = queue.offer("item", 5, TimeUnit.SECONDS); if (!added) { System.out.println("Timeout: queue full"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Consumer: Wait up to 2 seconds for element try { String item = queue.poll(2, TimeUnit.SECONDS); if (item != null) { processItem(item); } else { System.out.println("Timeout: no items"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ``` -------------------------------- ### Batch Processing with DisruptorBlockingQueue Source: https://github.com/conversant/disruptor/blob/master/_autodocs/README.md Shows how to efficiently process events in batches using DisruptorBlockingQueue. The queue is drained into a batch array for processing. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(10000); Event[] batch = new Event[1000]; while (true) { int count = queue.drainTo(batch); if (count > 0) { processBatch(batch, count); } } ``` -------------------------------- ### DisruptorBlockingQueue(int capacity, Collection c) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/DisruptorBlockingQueue.md Creates a new blocking queue with the given capacity and initializes it with elements from the provided collection. ```APIDOC ## DisruptorBlockingQueue(int capacity, Collection c) ### Description Creates a new blocking queue and initializes it with elements from the provided collection. ### Parameters #### Path Parameters - **capacity** (int) - Required - Initial queue capacity; will be rounded up to the next power of 2 - **c** (Collection) - Required - Collection of elements to populate the queue ### Request Example ```java List initial = Arrays.asList("a", "b", "c"); DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>(1024, initial); ``` ``` -------------------------------- ### Configure SpinPolicy for Blocking Queues and Stacks Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Initialize blocking queues and stacks with a specific SpinPolicy to control thread behavior during contention. Defaults to WAITING if not specified. ```java new DisruptorBlockingQueue<>(1024, SpinPolicy.SPINNING); new PushPullBlockingQueue<>(256, SpinPolicy.WAITING); new ConcurrentStack<>(512, SpinPolicy.BLOCKING); ``` -------------------------------- ### Configure DisruptorBlockingQueue for Server Applications Source: https://github.com/conversant/disruptor/blob/master/_autodocs/configuration.md Configures a DisruptorBlockingQueue for general server applications, balancing capacity and using the default WAITING spin policy. This provides a stable and efficient approach for typical server workloads. ```java DisruptorBlockingQueue queue = new DisruptorBlockingQueue<>( 1024, // Moderate capacity SpinPolicy.WAITING // Default balanced approach ); ``` -------------------------------- ### add(E e) Source: https://github.com/conversant/disruptor/blob/master/_autodocs/api-reference/PushPullBlockingQueue.md Adds an element to the queue. This method throws an IllegalStateException if the queue is full, unlike the offer() method which returns false. ```APIDOC ## add(E e) ### Description Adds an element to the queue, throwing an exception if full. ### Method `add(E e)` ### Parameters #### Path Parameters - **e** (E) - Required - Element to add ### Response #### Success Response (boolean) - **true** - always true on success #### Throws - `IllegalStateException` - if queue is full ```