Professional Documents
Culture Documents
The preceding code shows exactly how a stateful session bean works. Two books are created and
added to a shopping cart of a stateful component. At the end, the checkOutShoppingCart()
method relies on the maintained state and can check out the two books. When a client invokes a
stateful session bean in the server, the EJB container needs to provide the same instance for each
subsequent method invocation. Stateful beans cannot be reused by other clients. Figure 3. 2
shows the one-to-one correlation between a bean instance and a client. As far as the developer is
concerned, no extra code is needed, as the EJB container automatically manages this one-to-one
correlation.
private Cache() {}
return instance;
if (!cache.containsKey(id))
cache.put(id, object);
if (cache.containsKey(id))
cache.remove(id);
}
if (cache.containsKey(id))
return cache.get(id);
else
return null;
}
}
EJB 3.1 introduced the singleton session bean, which follows the singleton design pattern. Once
instantiated, the container makes sure there is only one instance of a singleton for the duration of
the application. An instance is shared between several clients, as shown in Figure 3.3. Singletons
maintain their state between client invocations.