Quantcast
Channel: Scratch Where It's Itching
Viewing all articles
Browse latest Browse all 73

Rocket Anti-Pattern

$
0
0
At my presentation at Devoxx Paris this year, The Thread Awakens, I introduced several Patterns related to multithreading. Since it was a quickie, I had only 15 minutes to talk about 15 Patterns. That got me to think: maybe some people would like me to develop a bit more on them. Or maybe some other people would prefer to read about them than to watch me on video (I, for instance, would not watch myself on video…). Or, maybe more surprisingly, some people do not speak french (it might happen). So for all those people, I will introduce my Patterns in my blog, one at a time. And I’ll start with the Rocket Anti-Pattern.

Data in an application travels like a rocket. It crosses several application layers in the same way that rockets cross several layers of atmosphere before reaching space. Data might enter through a database layer, or a communication layer, then cross one or several business layers, before leaving the application through another communication layer, or a user interface. But sometimes, the analogy goes a bit too far.

When you are watching a rocket leaving, you follow it from the moment it ignites to the moment it disappear into the sky. The Java equivalent would be:

public class Comm {public void onMessage(Message m) {
        Data data = transcode(m);
        calculator.calculatePrice(data);
        display.show(data);
    }
}public class Calculator {public void calculatePrice(Data data) {
        data.price = data.unitPrice * data.quantity;
    }
}public class Display {public void show(Data data) {
        SwingUtilities.invokeAndWait(() -> table.addRow(data));
    }
}

What you see here, is a Message that is transcoded into a Data class, then a price is calculated, and finally, Data is displayed on the user interface. You’ll notice the use of SwingUtilities.invokeAndWait(), which might be too much, but you’ll get the point: the same thread is doing almost everything, and won’t return before data has crossed all the layers.

The drawback of this method appears if you get many messages. In a usual communication layer, messages will fill a buffer, where they’ll wait to be handled. If the handling thread is too slow (like when it waits for data to cross all the layers), buffer will get overflooded, and you’ll start to loose messages. And that’s not what you want.

If you wish to avoid the Rocket Anti-Pattern, you’ll need to use the Paratrooper Model, which I’ll describe in my next entry. Stay tuned!


Viewing all articles
Browse latest Browse all 73

Trending Articles