5.9. Optimizing message transfer with asynchronous sessions in C++

5.9. Optimizing message transfer with asynchronous sessions in C++

When doing many message transfers, we can significantly improve our speed by using an asynchronous session. With a synchronous session, every call to messageTransfer() waits for confirmation before returning. An asynchronous session assumes that transfers succeed, and returns without waiting for confirmation. In general, applications should use a synchronous session for everything except for message transfer, because asynchronous sessions can cause a variety of rather confusing programming errors, and there is little performance improvement except when doing message transfer.For message transfer, cast the synchronous session to an asynchronous session to improve speed, and use Session.sync() to wait for all pending operations to complete and detect any errors before going on to do other operations:

#include <qpid/client/AsyncSession.h>

for (int i=0; i<10; i++) {
  stringstream message_data;
  message_data << "Message " << i;

  message.setData(message_data.str());
  async(session).messageTransfer(arg::content=message, arg::destination="amq.direct");
}

session.sync();

When using asynchronous sessions, many assumptions programmers generally make do not hold. For instance:

sync() allows you to wait for all commands issued so far to complete. You can also test the outcome of individual commands by using the objects they return, see the Doxygen documentation for details. Asynchronous sessions should be used for commands that are performance-critical, and these sections should be thoroughly tested. Synchronous sessions obey the rules most programmers are used to: they return only when the command is complete and throw an exception immediately if the command failed.