Disruptor
Since Camel 2.12
Both producer and consumer are supported
The Disruptor component provides asynchronous SEDA behavior similarly to the standard SEDA component. However, it uses a Disruptor instead of a BlockingQueue used by the standard SEDA. Alternatively, this component supports a 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
BrowsableEndpointinterface. 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.
-
While a Disruptor has no consumer, a reconfiguration (for example when its endpoint is added again) keeps the pending exchanges in a buffer for the first consumer. The queue can then hold more than
sizeexchanges:getRemainingCapacity()does not count the buffered ones, andgetPendingExchangeCount()does. -
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
pollTimeoutoption 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:
<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.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Disruptor component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The number of exchanges the ring buffer of a queue holds when its endpoint does not set the size option, rounded up to the next power of two as the LMAX Disruptor requires. It applies to the ring buffers created after it is set. | 1024 | int | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
The default of the endpoint option concurrentConsumers: the number of threads that process the exchanges of each consumer. | 1 | int | |
The default of the endpoint option multipleConsumers: whether more than one consumer may consume from the same endpoint, each one receiving every exchange (publish-subscribe). | false | boolean | |
The default of the endpoint option waitStrategy: the LMAX Disruptor wait strategy the consumer threads use to wait for new exchanges (Blocking, Sleeping, Yielding or BusySpin). Enum values:
| Blocking | DisruptorWaitStrategy | |
The default of the endpoint option blockWhenFull: whether a producer waits for a free slot when the ring buffer is full (true), or fails at once (false). | true | boolean | |
The default of the endpoint option producerType: the LMAX Disruptor producer type of the ring buffer, Multi (any number of threads publish) or Single (one thread at a time publishes). Enum values:
| Multi | DisruptorProducerType | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean |
Endpoint Options
The Disruptor endpoint is configured using URI syntax:
disruptor:name
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The number of exchanges the ring buffer holds, rounded up to the next power of two as the LMAX Disruptor requires (for example 1000 becomes 1024). When not set, the bufferSize option of the component applies. All the endpoints with the same name share one ring buffer, created by the first of them: creating an endpoint whose size differs from the size of the existing ring buffer fails, and an endpoint without a size uses the existing one. To be sure of the size, set it on all the endpoints of the name. | 1024 | int | |
The number of threads that process the exchanges of each consumer of this endpoint. Each thread is an LMAX Disruptor event handler that sees every exchange and processes only those whose ring buffer sequence modulo concurrentConsumers is its index, so the exchanges are spread round-robin over the threads. With multipleConsumers, each consumer has this number of threads. A value greater than 500 is rejected. | 1 | int | |
Whether more than one consumer (route) may consume from this endpoint, for publish-subscribe messaging: each consumer receives its own copy of every exchange. A producer that waits for the reply waits until all the consumers are done, and gets the failure of a consumer that failed (the results are not aggregated). When false, starting a second consumer on this endpoint fails. | false | boolean | |
The LMAX Disruptor wait strategy the consumer threads use to wait for new exchanges: Blocking (waits on a lock and condition, the least CPU), Sleeping (spins, then calls Thread.yield(), then parks for 100 nanoseconds at a time), Yielding (spins, then calls Thread.yield()) or BusySpin (spins without pause, the lowest latency, keeps a CPU core busy per thread). The ring buffer uses the wait strategy of the first endpoint created with its name; the value of the other endpoints is ignored. Enum values:
| Blocking | DisruptorWaitStrategy | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Whether a producer that sends to a full ring buffer waits for a free slot (true), or fails the exchange at once with an IllegalStateException (false). The wait has no timeout and does not respond to thread interrupts. When not set, the defaultBlockWhenFull option of the component applies, which is true. | false | boolean | |
The LMAX Disruptor producer type of the ring buffer: Multi, which any number of threads can publish to at the same time, or Single, which is faster but only correct when one thread at a time publishes (Camel rejects a second producer on this endpoint, but does not stop several threads from using one producer). The ring buffer uses the producer type of the first endpoint created with its name; the value of the other endpoints is ignored. Enum values:
| Multi | DisruptorProducerType | |
How long (in milliseconds) a producer that waits for the consumer (see waitForTaskToComplete) waits for the exchange to complete, before it fails the exchange with an ExchangeTimedOutException. The consumer then skips the exchange if it has not started it yet. The time a producer waits for a free slot of a full ring buffer does not count. Use 0 or a negative value to wait without limit. | 30000 | long | |
Whether the producer waits for the consumer to complete the exchange before it continues: Always, Never, or IfReplyExpected, which waits only when the exchange expects a reply (InOut). A producer that waits (see the timeout option) gets the result of the consumer, or with multipleConsumers only the failure of a consumer that failed. The exchange property CamelAsyncWait overrides this option for one exchange. Enum values:
| IfReplyExpected | WaitForTaskToComplete | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean |
Message Body
The message body at each side of the Disruptor component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The body the producer sent. |
Producer input |
| |
Producer output |
| Unchanged for a message that expects no reply (InOnly). A message that expects one (InOut), or waitForTaskToComplete=Always, waits for the body the disruptor route ends with; with more than one consumer route (multipleConsumers) the body stays unchanged.
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
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:
| 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 | 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 | This strategy is a good compromise between performance and CPU resource without incurring significant latency spikes. |
Using Request/Reply
The Disruptor component supports using Request/Reply, where the caller will wait for the Async route to complete. For instance:
-
Java
-
XML
-
YAML
from("mina:tcp://0.0.0.0:9876?textline=true&sync=true").to("disruptor:input");
from("disruptor:input").to("bean:processInput").to("bean:createResponse"); <route>
<from uri="mina:tcp://0.0.0.0:9876?textline=true&sync=true"/>
<to uri="disruptor:input"/>
</route>
<route>
<from uri="disruptor:input"/>
<to uri="bean:processInput"/>
<to uri="bean:createResponse"/>
</route> - route:
from:
uri: mina:tcp://0.0.0.0:9876
parameters:
textline: true
sync: true
steps:
- to:
uri: disruptor:input
- route:
from:
uri: disruptor:input
steps:
- to:
uri: bean:processInput
- to:
uri: 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:
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:
from("disruptor:stageName").threads(5).process(...) Can wind up with adding a normal 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.
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.
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.
<!-- 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. The message is completed once all consumers are done with it (as with SEDA): if a consumer fails, its failure is copied back to the message (the results of the consumers are not aggregated), so a producer waiting for the reply gets the failure, and the on completions of the caller run, only when all consumers are done. 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.
public class FooEventConsumer {
@EndpointInject("mock:result")
private ProducerTemplate destination;
@Consume(ref = "foo")
public void doSomething(String body) {
destination.sendBody("foo" + body);
}
}