with a focus on asynchronous C++ server-side programming

Currently I’m working with Python’s “event-driven networking engine” Twisted and Boost ASIO. Both libraries make use of the Reactor and Proactor design patterns.

Finding information on the difference between the two patterns was difficult. The best source I found was Pattern-Oriented Software Architecture Volume 2 (Patterns for Concurrent and Networked Objects) by Schmidt, Stal, Rohnert, and Buschmann.

I was interested in understanding the difference between Reactors and Proactors while learning about Linux system calls used in the patterns (like epoll).

This is the first post in a series where I’ll share what I’ve learned about the Reactor design pattern. In later posts we’ll go over the Proactor pattern.

A Reactor allows you to register event handlers. In this example, when you receive the event signified by “one” it will fire the callback printing “one handler called!”. Similarly there is an event handler for “two”. In the real world these would more likely be events triggered by client connects to a server or responses from an HTTP request, for example.

Reactors need to manage what is known as a synchronous event demultiplexer like epoll or select. Epoll, which is what we’ll use in this example, is described in the Linux man pages as an “I/O event notification facility”. It is synchronous in that when we call wait it blocks: our application stops processing when wait is called until the operating system lets us know an event has occurred. In this example we tell epoll to let us know when input has been entered by registering interest in the stdin file descriptor. Once we are notified by epoll that a subscribed-to event has arrived we fire off the corresponding handler. In essence this is what a Reactor does: it utilizes a system call like epoll or select to listen to events and fires off a handler when it receives them.

In the following source code our simplified Reactor class manages an Epoll instance. The reactor waits for epoll to let us know something was entered on standard input and then fires off the matching event handler.

Reactors can be beneficial in that they lack the overhead (context switching, shared mutable data safety, etc.) associated with servers that spawn a thread per connection. In the case of a Reactor it is important that the handler functionality is able to complete quickly so that the application can return to servicing other events as soon as possible.

With C++17 you can create a copy of *this by doing the following. Note that doing so no longer allows you to use the original pointer this inside the lambda body (unless you created a separate lvalue for it).

Consider a service method in your Spring Boot project that both writes to a queue and a database. If your write to the queue is successful, yet the database call throws an exception, you might not want to keep that item on the queue. Writing the code for this yourself could be cumbersome. Fortunately, Spring provides the handy @Transactional annotation. In this post we’ll look at how to write an integration test for methods using this annotation.

@SpringApplicationConfiguration loads and configures an ApplicationContext for integration tests. It’s similar to @ContextConfiguration but uses Spring Boot’s SpringApplicationContextLoader. We provide the Application and TestConfig classes. Application is your main Spring Boot entry-point class that contains SpringApplication.run. TestConfig is a custom class we’ll use later to provide mocks for our test.

Use @WebAppConfiguration over @WebIntegrationTest in this example since we will not be testing the HTTP entrypoint into our application (through REST).

@DirtiesContext is necessary here. What it does is mark the ApplicationContext as dirty, thus requiring it to be reloaded for the next integration test. We are going to be using a mocked bean. Since Spring caches the ApplicationContext between test runs, we want to ensure it is not cached with this mocked bean.

@Slf4j is a lombok convenience annotation to prevent us from typing the long-winded:

Finally extending AbstractTestNGSpringContextTests sets our ApplicationContext up for support with a TestNG environment. Alternatively, you could extend AbstractJUnit4SpringContextTests if you want to use JUnit4.

@Configuration marks our class for use by the Spring context to gather beans.

What we’re doing here is creating a mocked implementation of our queue client. Why do we want a mocked version? Because we are going to simulate the queue client throwing an exception. We want to ensure that when this exception is thrown, that the database entry is not persisted. Indeed, we want the database transaction to rollback.

We inject our service and repository. Next, we inject our mocked queue client. I use the @Qualifier so I can give the variable name a prefix of “mocked” (as in mockedRabbitTemplateWithExchange). Make sure that people know you are using a mocked version both in this test AND inside your spring boot application.

Finally, the test tells the queue client to throw an exception when it is used. Since it threw an exception, we don’t want our database write to persist – even though the exception occurs after the database call has been made. We check the records in the database to ensure that it has indeed not been written.

Let’s create a Dragon “class” in Javascript that we can use to inherit from.

var Dragon = function(color) {
this.color = color;
}
// prototype is a special object used for inheritance in Javascript.
// We could have added the attack method as a member variable similar to color, however we'll use it on the prototype
// later.
Dragon.prototype.attack = function() {
console.log("The " + this.color + " dragon breathes fire!");
}
var dragon = new Dragon("red");
dragon.attack(); // The red dragon breathes fire!

Calling “new Dragon();” creates a new object that inherits anything set on the Dragon.prototype object. First, Javascript will check to see if a property exists on Dragon itself. If it doesn’t exist on Dragon, it will check Dragon.prototype. We can check to see whether properties exist on Dragon or it’s prototype as follows:

dragon.hasOwnProperty("color"); // true
dragon.hasOwnProperty("attack"); // false, this is not an "own" property - it's part of the prototype

The hasOwnProperty method differentiates between an objects properties and those that were inherited from it’s prototype. Where does the “hasOwnProperty” method come from? The hasOwnProperty method comes from Object.prototype:

This tail-recursive version is more efficient because it simply accumulates the Fibonacci computation in an argument to the function (a+b). No longer do we need to store a tremendous amount of calculations on the stack – it’s now treated much like an iterative for loop.

Finally, there exists a closed-form formula to calculate the nth Fibonacci number. Using this formula, we can arrive at the function:

Our result, which merges the users and orders tables by matching the user_id field, gets the user_id, first_name, last_name, and total, and finally sorts them by user_id:

user_id

first_name

last_name

total

2

Mark

Smith

500.99

2

Mark

Smith

59.99

3

Tom

Williamson

60

An INNER JOIN is similar to the intersection of a set in mathematics, or the intersection of a Venn Diagram. The result includes all the rows with a match on users.user_id = orders.user_id. The result will not include any rows from the left or right table (users and orders, respectively) that do not contain a match within the ON clause.

A LEFT OUTER JOIN will return the same result as an INNER JOIN, however it will also include every row in the left table (users), even if there is no match within the ON clause. Fields that do not match will be marked with NULL:

Likewise a RIGHT OUTER JOIN will include all of the rows from the right table (orders) and mark non-matches with a NULL:

user_id

first_name

last_name

total

2

Mark

Smith

500.99

2

Mark

Smith

59.99

3

Tom

Williamson

60

In this particular example, every row in the right table (orders) has a match and no NULL fields are returned.

Finally, if not evident from the examples given above, it should be noted that LEFT and RIGHT refer to the order of the tables listed in the SQL statement. In our example, users is listed first (becoming the left table) and orders is listed next (effectively making it the right table).