State Design

Continuing on with the Forethought business logic, I want to spend some time on the issue of stateful versus stateless beans. I refer to it as an issue because it almost always manages to come up when working with session beans, and can have a drastic effect on your application’s performance. Specifically, stateless session beans are much more efficient than stateful session beans.

For a more detailed discussion on the issue, you can check out Richard Monson-Haefel’s Enterprise JavaBeans, which spends a great deal of print on how a container handles these two kinds of beans. I’ll briefly sum up the relevant portions here. A stateless session bean is a very lightweight bean, since it needs to carry around only EJB-mandated variables, not programmer-defined ones. As a result, most containers have pools of stateless beans. Because no single client needs to have access to a specific stateless bean instance (no state is being kept, remember), a single instance can serve two, three, ten, or even a hundred clients. This allows the bean pool to be kept small, and negates a frequent need to grow or shrink the pool, which would take valuable processor cycles.

A stateful bean is just the opposite: an instance is tied to the client that invoked its create( ) method. This means that an instance must exist for every client accessing the stateful bean. Therefore, the bean pools must be larger, or must frequently be grown as more requests come in. The end result is longer process ...

Get Building Java Enterprise Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.