Welcome!

Eclipse Authors: Carmen Gonzalez, Kevin Jackson, Lori MacVittie, Mark R. Hinkle, Natalie Lerner

Related Topics: Java, XML, SOA & WOA, Eclipse, AJAX & REA, Apache

Java: Article

The Disruptor Framework: A Concurrency Framework for Java

Rediscovering the Producer-Consumer Model with the Disruptor

Let's start with the basic question: What is the disruptor? The disruptor is a concurrency framework for Java that allows data sharing between threads. The age old way of coding a producer-consumer model is to use a queue as the buffer area between the producer and the consumer, where the producer adds data objects to the queue, which are in turn processed by the consumer. However, such a model does not work well at the hardware level and ends up being highly inefficient. The disruptor in its simplest form replaces the queue with a data structure known as the ‘ring buffer'. Which brings us to the next question, what is the ring buffer? The ring buffer is an array of fixed length (which must be a power of 2), it's circular and wraps. This data structure is at the core of what makes the disruptor super fast.

Let's explore a simple everyday scenario in enterprise architectures. A producer (let's call it the publisher) creates data and stores it in the queue. Two immediate consumers (let's call them fooHandler and barHandler) consume the data and make updates to it. Once these 2 processors are done with a piece of data, it is then passed on to a third consumer (let's call it fooBarHandler) for further processing. In a concurrent processing system using legacy techniques, coding this architecture would involve a crisscross of queues and numerous concurrency challenges, such as dealing with locks, CAS, write contention, etc. The disruptor on the other hand immensely simplifies such a scenario by providing a simple API for creating the producer, consumers and ring buffer, which in turn relieve the developer of all concerns surrounding handling concurrency and doing so in an efficient manner. We shall now explore how the disruptor works its magic and provides a reliable messaging framework.

Writing to the ring buffer

Looking at the figure above, we find ourselves in the middle of the action. The ring buffer is an array of length 4 and is populated with data items - 4,5,6 and 7, which in the case of the disruptor are known as events. The square above the ring buffer containing the number 7 is the current sequence number, which denotes the highest populated event in the ring buffer. The ring buffer keeps track of this sequence number and increments it as and when new events are published to it. The fooHandler, barHandler and fooBarHandler are the consumers, which in disruptor terminology are called ‘event processors'. Each of these also has a square containing a sequence number, which in the case of the event processors denotes the highest event that they have consumed/processed so far. Thus its apparent that each entity (except the publisher) tracks its own sequence number and thus does not need to rely on a third party to figure out which is the next event its after.

The publisher asks the ring buffer for the next sequence number. The ring buffer is currently at 7, so the next sequence number would be 8. However, this would also entail overwriting the event with sequence number 4 (since there are only 4 slots in the array and the oldest event gets replaced with the newest one). The ring buffer first checks the most downstream consumer (fooBarHandler) to determine whether it is done processing the event with sequence number 4. In this case, it has, so it returns the number 8 to the publisher. In case fooBarHandler was stuck at a sequence number lower than 4, the ring buffer would have waited for it to finish processing the 4th event before returning the next sequence number to the publisher. This sequence number helps the publisher identify the next available slot in the ring buffer by performing a simple mod operation. indexOfNextAvailableSlot = highestSeqNo%longthOfRingBuffer, which in this case is 0 (8%4). The publisher then claims the next slot in the ring buffer (via a customizable strategy depending on whether there is a single or multiple publishers), which is currently occupied by event 4, and publishes event 8 to it.

Reading from the ring buffer by immediate consumers

The figure above shows the state of operations after the publisher has published event 8 to the ring buffer. The ring buffer's sequence number has been updated to 8 and now contains events 5,6,7 and 8. We see that foohandler, which has processed events upto 7, has been waiting (using a customizable strategy) for the 8th event to be published. Unlike the publisher though, it does not directly communicate with the ring buffer, but uses an entity known as the ‘sequence barrier' to do so on its behalf. The sequence barrier let's fooHandler know that the highest sequence number available in the ring buffer is now 8. FooHandler may now get this event and process it.

Similarly, barHandler checks the sequence barrier to determine whether there are any more events it can process. However, rather than just telling barHandler that the next (6th) event is up for grabs, the sequence barrier returns the highest sequence number present in the ring buffer to barHandler too. This way, barHandler can grab events 6,7,8 and process them in a batch before it has to enquire about further events being published. This saves time and reduces load.

Another important thing to note here is that in the case of multiple event processors, any given field in the event object must only be written to by any one event processor. Doing so prevents write contention, and thus removes the need for locks or CAS.

Reading from the ring buffer by downstream consumers

A few moments after the set of immediate consumers grab the next set of data, the state of affairs looks like the figure above. fooHandler is done processing all 8 available events (and has accordingly updated its sequence number to 8), whereas barHandler, being the slow coach that it is, has only processed events upto number 6 (and thus has updated sequence number to 6). We now see that fooBarHandler, which was done processing events upto number 5 at the start of our examination, is still waiting for an event higher than that to process. Why did its sequence barrier not inform it once event 8 was published to the ring buffer? Well, that is because downstream consumers don't automatically get notified of the highest sequence number present in the ring buffer. Their sequence barriers on the other hand determine the next sequence number they can process by calculating the minimum sequence number that the set of event processors directly before them have processed. This helps ensure that the downstream consumers only act on an event once its processing has been completed by the entire set of upstream consumers. The sequence barrier examines the sequence number on fooHandler (which is 8) and the sequence number on barHandler (which is 6) and decides that event 6 is the highest event that fooBarHandler can process. It returns this info to fooBarHandler, which then grabs event 6 and processes it. It must be noted that even in the case of the downstream consumers, they grab the events directly from the ring buffer and not from the consumers before them.

Well, that is about all you would need to know about the working of the disruptor framework to get started. But while this is all well and good in theory, the question still remains, how would one code the above architecture using the disruptor library? The answer to that question lies below.

Coding the disruptor

public final class FooBarEvent {
private double foo=0;
private double bar=0;
public double getFoo(){
return foo;
}
public double getBar() {
return bar;
}
public void setFoo(final double foo) {
this.foo = foo;
}
public void setBar(final double bar) {
this.bar = bar;
}
public final static EventFactory<FooBarEvent> EVENT_FACTORY
= new EventFactory<FooBarEvent>() {
public FooBarEvent newInstance() {
return new FooBarEvent();
}
};
}

The class FooBarEvent, as the name suggests, acts as the event object which is published by the publisher to the ring buffer and consumed by the eventProcessors - fooHandler, barHandler and fooBarHandler. It contains two fields ‘foo' and ‘bar' of type double, along with their corresponding setters/getters. It also contains an entity ‘EVENT_FACTORY' of type EventFactory, which is used to create an instance of this event.

public class FooBarDisruptor {           
public static final int RING_SIZE=4;
public static final ExecutorService EXECUTOR
=Executors.newCachedThreadPool();

final EventTranslator<FooBarEvent> eventTranslator
=new EventTranslator<FooBarEvent>() {
public void translateTo(FooBarEvent event,
long sequence) {
double foo=event.getFoo();
double bar=event.getBar();
system.out.println("foo="+foo
+", bar="+bar
+" (sequence="+sequence+")");
}
};

final EventHandler<FooBarEvent> fooHandler
= new EventHandler<FooBarEvent>() {
public void onEvent(final FooBarEvent event,
final long sequence,
final boolean endOfBatch)
throws Exception {
double foo=Math.random();
event.setFoo(foo);
System.out.println("setting foo to "+foo
+" (sequence="+sequence+")");
}
};

final EventHandler<FooBarEvent> barHandler
= new EventHandler<FooBarEvent>() {
public void onEvent(final FooBarEvent event,
final long sequence,
final boolean endOfBatch)
throws Exception {
double bar=Math.random();
event.setBar(bar);
System.out.println("setting bar to "+bar
+" (sequence="+sequence+")");
}
};

final EventHandler<FooBarEvent> fooBarHandler
= new EventHandler<FooBarEvent>() {
public void onEvent(final FooBarEvent event,
final long sequence,
final boolean endOfBatch)
throws Exception {
double foo=event.getFoo();
double bar=event.getBar();
System.out.println("foo="+foo
+", bar="+bar
+" (sequence="+sequence+")");
}
};

public Disruptor setup() {
Disruptor<FooBarEvent> disruptor =
new Disruptor<FooBarEvent>(FooBarEvent.EVENT_FACTORY,
EXECUTOR,
new SingleThreadedClaimStrategy(RING_SIZE),
new SleepingWaitStrategy());
disruptor.handleEventsWith(fooHandler, barHandler).then(fooBarHandler);
RingBuffer<FooBarEvent> ringBuffer = disruptor.start();             
return disruptor;
}

public void publish(Disruptor<FooBarEvent> disruptor) {
for(int i=0;i<1000;i++) {
disruptor.publishEvent(eventTranslator);
}
}

public static void main(String[] args) {
FooBarDisruptor fooBarDisruptor=new FooBarDisruptor();
Disruptor disruptor=fooBarDisruptor.setup();
fooBarDisruptor.publish(disruptor);
}
}

The class FooBarDisruptor is where all the action happens. The ‘eventTranslator' is an entity which aids the publisher in publishing events to the ring buffer. It implements a method ‘translateTo' which gets invoked when the publisher is granted permission to publish the next event. fooHandler, barHandler and fooBarHandler are the event processors, and are objects of type ‘EventHandler'. Each of them implements a method ‘onEvent' which gets invoked once the event processor is granted access to a new event. The method ‘setup' is responsible for creating the disruptor, assigning the corresponding event handlers, and setting the dependency rules amongst them. The method ‘publish' is responsible for publishing a thousand events of the type ‘FooBarEvent' to the ring buffer.

In order to get the above code to work, you must download the disruptor jar file from http://code.google.com/p/disruptor/downloads/list and include the same in your classpath.

Conclusion
The disruptor is currently in use in the ultra efficient LMAX architecture, where it has proven to be a reliable model for inter thread communication and data sharing, reducing the end to end latency to a fraction of what queue based architectures provided. It does so using a variety of techniques, including replacing the array blocking queue with a ring buffer, getting rid of all locks, write contention and CAS operations (except in the scenario where one has multiple publishers), having each entity track its own progress by way of a sequence number, etc. Adopting this framework can greatly boost a developer's productivity in terms of coding a producer-consumer pattern, while at the same time aid in creating an end product far superior in terms of both design and performance to the legacy queue based architectures.

More Stories By Sanat Vij

Sanat Vij is a professional software engineer currently working at CenturyLink. He has vast experience in developing high availability applications, configuring application servers, JVM profiling and memory management. He specializes in performance tuning of applications, reducing response times, and increasing stability.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, will describe how to revoluti...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.