The good news is that you can emulate asynchronous callbacks in Java. In fact, I did just that recently with a library I’ve dubbed Ahoy!, which is an asynchronous SQS adapter for AWS’s Java SQS library.
For the uninitiated, SQS is a cloud based messaging platform – with SQS you can create queues and put messages onto those queues, which can then be read – later or immediately by some other process or the same exact process. All of this leverages Amazon’s massively redundant architecture to offer extremely high availability in the face of concurrent access.
Asynchronous callbacks in Java can be achieved with two features: anonymous classes (containing one method) and Java’s
Because Java doesn’t allow you to pass functions (or methods) easily as a parameter, to simulate a callback, you can create an interface that contains one method, which basically mimics a function. In the case of Ahoy, there are two interfaces:
MessageReceivedCallback – both have one method:
onReceive respectively. Accordingly, Ahoy!”s primary class, dubbed
SQSAdapter exposes two simple methods:
receive and both take their related callback interface.
The most straightforward callback to understand is the
receive method. As you can imagine,
receive is intended to handle behavior when a message is received off of a particular queue. Thus, the
receive method is defined as follows:
MessageReceivedCallback interface looks like this:
1 2 3
onReceive method takes a message id (which is particular to SQS) and the message itself – which in the case of SQS is always a
String can hold anything you want, keep in mind: JSON, XML, byte sequence, etc).
Thus, clients of Ahoy! provide the intended behavior for a message when it is received. This behavior could be to write something to a database, generate another message and send it on another queue, you name it.
Now the interesting part is the implementation of Ahoy!’s
receive method. To achieve asynchronocity, I employed Java’s
java.util.concurrent package, which sadly, seems to be under appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
With a fixed Thread pool, a thread is created, which waits for messages to arrive on a particular queue; when one shows up, the passed in
MessageReceivedCalledback is invoked for each message.
For an example of how this works for clients of Ahoy!, here’s a test case that verifies the execution of the callback:
1 2 3 4 5 6 7 8
Likewise, sending a message is similar – a new
Runnable instance is created, which sends a particular message and invokes the passed in
onSend method, passing in the newly sent messages’s id.
1 2 3 4 5 6 7 8 9 10
Incidentally, the AWS Java SDK does provide an asynchronous client; however, this client’s implementation leverages Java’s Futures. While Futures are a neat concept, Ahoy!’s implementation is more convenient (at least for me and in the patterns of how I employ SQS) than Futures as there isn’t any polling involved once a message is sent or received.