Instrumenting asynchronous code
Using messaging between services is not the only way to implement asynchronous applications. Sometimes, the code within a single service is asynchronous. In environments like Node.js, it is the standard way of writing code and requires a different style of in-process context propagation.
In Java, the asynchronous code is often written with the use of futures and executors. In our Tracing Talk application, we have already used those APIs, only in the synchronous manner. For example, the KafkaService.sendMessage()
method calls the send()
function, which returns ListenableFuture
, a sign of the asynchronous API. We turn it back to synchronous by calling get()
and blocking until it is completed:
public void sendMessage(Message message) throws Exception {
ProducerRecord<String, Message> record =
new ProducerRecord<>(TOPIC, message);
kafkaTemplate.send(record).get();
}
The tracing implementation we used takes care of transferring the tracing...