In my previous entry, I was describing the Rocket Anti-Pattern, where one thread would handle too much work across several application layers, leading to communication buffer overflow and message loss.
To solve this problem, you can use the Paratrooper Model. When paratroopers jump from a plane, they are not waiting for the previous guy who jumped to land safely on the ground before jumping themselves. They are jumping as soon as they can after the guy that precedes them left the place. It should be the same with your data. The thread that receives and transcodes the messages should only do that and nothing else. It should work as fast as possible, and let another thread go on with the work in the next application layer, while concentrating on the next message. This way, we are building a sort of pipeline, with one or several worker threads in each application layer.
Here is an equivalent of the application shown in the previous entry, using our new model:
public class Comm {
public void onMessage(Message m) {
Data data = transcode(m);
calculator.push(data);
}
}
}
public class Calculator {
public void push(Data data) {
executor.execute(() -> calculatePrice(data));
}
}
public void calculatePrice(Data data) {
data.price = data.unitPrice * data.quantity;
Display.show(data);
}
}
}
public class Display {
public void show(Data data) {
SwingUtilities.invokeLater(() -> table.addRow(data));
}
}
}
Each class represents a layer, and propagates the data to the next layer, which will in turn ask the layer’s dedicated thread to handle it.
To implement this model, you will have to use the Marsupilami Pattern. Wait for it!