= Disruptor Component
:doctitle: Disruptor
:shortname: disruptor
:artifactid: camel-disruptor
:description: Provides asynchronous SEDA behavior using LMAX Disruptor.
:since: 2.12
:supportlevel: Stable
:tabs-sync-option:
:component-header: Both producer and consumer are supported
//Manually maintained attributes
:camel-spring-boot-name: disruptor

*Since Camel {since}*

*{component-header}*

The Disruptor component provides asynchronous
https://en.wikipedia.org/wiki/Staged_event-driven_architecture[SEDA] behavior similarly to the
standard SEDA component.
However, it uses a https://github.com/LMAX-Exchange/disruptor[Disruptor] instead of a
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html[BlockingQueue]
used by the standard xref:seda-component.adoc[SEDA].
Alternatively, this component supports a xref:disruptor-vm-component.adoc[disruptor-vm] endpoint.

The main advantage of choosing to use the Disruptor component over the
SEDA is performance in use cases where there is high
contention between producer(s) and/or multicasted or concurrent
Consumers. In those cases, significant increases in throughput and
reduction of latency has been observed. Performance in scenarios without
contention is comparable to the SEDA component.

The Disruptor is implemented with the intention of mimicking the
behavior and options of the SEDA component as much as possible.
The main differences between them are the following:

* The buffer used is always bounded in size (default 1024 exchanges).
* As the buffer is always bounded, the default behavior for the
Disruptor is to block while the buffer is full instead of throwing an
exception. This default behavior may be configured on the component
(see options).
* The Disruptor endpoints don't implement the `BrowsableEndpoint`
interface. As such, the exchanges currently in the Disruptor can't be
retrieved, only the number of exchanges.
* The Disruptor requires its consumers (multicasted or otherwise) to be
statically configured. Adding or removing consumers on the fly requires
complete flushing of all pending exchanges in the Disruptor.
* As a result of the reconfiguration: Data sent over a Disruptor is
directly processed and 'gone' if there is at least one consumer, late
joiners only get new exchanges published after they've joined.
* The `pollTimeout` option is not supported by the Disruptor component.
* When a producer blocks on a full Disruptor, it does not respond to
thread interrupts.

Maven users will need to add the following dependency to their `pom.xml`
for this component:

[source,xml]
------------------------------------------------------------
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-disruptor</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
------------------------------------------------------------

== URI format

-----------------------------
 disruptor:someId[?options]
-----------------------------

Where _someId_ can be any string that uniquely identifies the
endpoint within the current CamelContext.

== Options

// component-configure options: START

// component-configure options: END

// component options: START
include::partial$component-configure-options.adoc[]
include::partial$component-endpoint-options.adoc[]
// component options: END

// endpoint options: START

// endpoint options: END

== Usage

=== Wait strategies

The wait strategy effects the type of waiting performed by the consumer
threads that are currently waiting for the next exchange to be
published. The following strategies can be chosen:

[width="100%",cols="10%,45%,45%",options="header",]
|=======================================================================
|Name |Description |Advice

|Blocking | Blocking strategy that uses a lock and condition variable for Consumers
waiting on a barrier. | This strategy can be used when throughput and low latency are not as
important as CPU resource.

|Sleeping |Sleeping strategy that initially spins then uses a `Thread.yield()`, and
eventually for the minimum number of nanos the OS and JVM will allow
while the Consumers are waiting on a barrier. |This strategy is a good compromise between performance and CPU resource.
Latency spikes can occur after quiet periods.

|BusySpin |Busy Spin strategy that uses a busy spin loop for Consumers waiting on a
barrier. |This strategy will use CPU resource to avoid _syscalls_ which can
introduce latency jitter. It is best used when threads can be bound to
specific CPU cores.

|Yielding |Yielding strategy that uses a `Thread.yield()` for Consumers waiting on a
barrier after an initially spinning. |This strategy is a good compromise between performance and CPU resource
without incurring significant latency spikes.
|=======================================================================

=== Using Request/Reply

The Disruptor component supports using xref:eips:requestReply-eip.adoc[Request/Reply],
where the caller will wait for the Async route to complete.
For instance:

.Request/Reply example with disruptor
[source,java]
------------------------------------------------------------------------------
from("mina:tcp://0.0.0.0:9876?textline=true&sync=true").to("disruptor:input");
from("disruptor:input").to("bean:processInput").to("bean:createResponse");
------------------------------------------------------------------------------

In the route above, we have a TCP listener on port 9876 that accepts
incoming requests. The request is routed to the _disruptor:input_
buffer. As it is a Request Reply message, we
wait for the response. When the consumer on the _disruptor:input_ buffer
is complete, it copies the response to the original message response.

=== Concurrent consumers

By default, the Disruptor endpoint uses a single consumer thread, but
you can configure it to use concurrent consumer threads. So instead of
thread pools, you can use:

.Concurrent consumers example
[source,java]
--------------------------------------------------------------
from("disruptor:stageName?concurrentConsumers=5").process(...)
--------------------------------------------------------------

As for the difference between the two, note that a thread pool can
increase/shrink dynamically at runtime depending on load. Whereas the
number of concurrent consumers is always fixed and supported by the
Disruptor internally, so performance will be higher.

=== Thread pools

Be aware that adding a thread pool to a Disruptor endpoint by doing
something like:

[source,java]
--------------------------------------------------
from("disruptor:stageName").thread(5).process(...)
--------------------------------------------------

Can wind up with adding a normal
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html[BlockingQueue]
to be used in conjunction with the Disruptor, effectively negating part
of the performance gains achieved by using the Disruptor. Instead, it is
advices to directly configure the number of threads that process messages on
a Disruptor endpoint using the concurrentConsumers option.

== Examples

=== Requests to async queue

In the route below, we use the Disruptor to send the request to this
async queue.
As such, it is able to send a _fire-and-forget_ message for further
processing in another thread, and return a constant reply in this thread
to the original caller.

[source,java]
-------------------------------------------------
public void configure() {
    from("direct:start")
        // send it to the disruptor that is async
        .to("disruptor:next")
        // return a constant response
        .transform(constant("OK"));

    from("disruptor:next").to("mock:result");
}
-------------------------------------------------

Here we send a _Hello World_ message and expect the reply to be _OK_.

[source,java]
-----------------------------------------------------------------
Object out = template.requestBody("direct:start", "Hello World");
assertEquals("OK", out);
-----------------------------------------------------------------

The "Hello World" message will be consumed from the Disruptor from
another thread for further processing. Since this is from a unit test,
it will be sent to a mock endpoint where we can do assertions in the
unit test.

=== Using multipleConsumers

In this example, we have defined two consumers and registered them as
spring beans.

[source,xml]
-------------------------------------------------------------------------------------------
<!-- define the consumers as spring beans -->
<bean id="consumer1" class="org.apache.camel.spring.example.FooEventConsumer"/>

<bean id="consumer2" class="org.apache.camel.spring.example.AnotherFooEventConsumer"/>

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <!-- define a shared endpoint which the consumers can refer to instead of using url -->
    <endpoint id="foo" uri="disruptor:foo?multipleConsumers=true"/>
</camelContext>
-------------------------------------------------------------------------------------------

Since we have specified multipleConsumers=true on the Disruptor foo
endpoint, we can have those two or more consumers receive their own copy
of the message as a kind of _publish/subscriber_ style messaging.
As the beans are part of a unit test, they simply send the message to a mock endpoint,
but notice how we can use _@Consume_ to consume from the Disruptor.

[source,java]
-------------------------------------------
public class FooEventConsumer {

    @EndpointInject("mock:result")
    private ProducerTemplate destination;

    @Consume(ref = "foo")
    public void doSomething(String body) {
        destination.sendBody("foo" + body);
    }

}
-------------------------------------------

=== Extracting disruptor information

If needed, information such as buffer size, etc. can be obtained without
using JMX in this fashion:

[source,java]
--------------------------------------------------------------------
DisruptorEndpoint disruptor = context.getEndpoint("disruptor:xxxx");
int size = disruptor.getBufferSize();
--------------------------------------------------------------------

// shared with disruptor-vm

include::spring-boot:partial$starter.adoc[]
