Java, stateless session bean

ejb-3.0jakarta-eejava

Stateless session beans do not maintain state. So does it mean they should not have instance variables?

Thanks,
Roger

Best Answer

The term "state" in this context is a little misleading. What it's referring to is conversational state, meaning if a client makes multiple calls the session bean has no way of knowing. Imagine a sequence of calls:

  • reserveSeatsOnFlight();
  • chooseMealPreference();
  • confirmBooking().

What you have there is conversational state, meaning the second call must be made to the same bean as the first call or it just won't make sense. That's what stateful session beans do.

Stateless session beans can have instance variables but those are essentially global. If you have a pool of stateless session beans (which you might or might not depending on what the container decides to do), those instances variables might or might not exist from one call to the next. So generally avoid instance variables. There are other mechanisms for that kind of thing.

Let me give you an example. Imagine this call in a stateless session bean:

public void bookFlight(List<Passsenger> passengers, FlightNumber flight, Date date) {
  ...
}

if you put in an instance variable to count the number of bookings and increment it on each call then subsequent calls might call different beans so will see different values. That's what I mean about it not necessarily making sense.

So going back to the first example, one way to handle this would be to pass state back to the caller:

public interface ReservationSystem {
  public int createNewBooking();
  public int reserveSeatsOnFlight(int bookingId, int seats);
  public int chooseMealPreference(int bookingId, ...)
  ...
}

See how the above no longer has conversational state? Well it does but it's now encapsulated in the bookingId that you pass around. A stateless session bean could retrieve the booking and continue from where another left off.