Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, stateless session bean

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

Thanks,
Roger

like image 749
gameover Avatar asked Dec 23 '22 06:12

gameover


2 Answers

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.

like image 58
cletus Avatar answered Feb 09 '23 03:02

cletus


I have often seen stateless session beans use local variables as a way to maintain "global" state within the bean (in order to avoid the onerous task of passing data from one method call within the object to another).

Having said that, these are essentially global variables within your object, and lend themselves to abuse (as they have been in most of the cases that I've seen as well). I'd tend to recommend avoiding them.

There can be cases where they are useful, though... do you have a specific usecase in mind?

like image 20
jsight Avatar answered Feb 09 '23 03:02

jsight