When do I instantiate stateless SessionBean instance variables

Discussions

EJB programming & troubleshooting: When do I instantiate stateless SessionBean instance variables

  1. Hi there,

    I just wonder when (and if) I should use and when I should instantiate instance variables in a stateless SessionBean (for performance optimization).

    E.g.: Does it make sense to have a JNDI InitalContext as a instance variable? And if so, when exactly would I call the constructor for that context:
    In the constructor of the SessionBean, in the setSessionContext method or in the create method?

    Thanx for any advice,

    Sebastian
  2. Here's a couple examples of using instance variable.

    - You can store the SessionContext in an instance variable.
    - store DataSource object in instance variable after you perform the JNDI datasource lookup one time and re-use it to getConnection for each of the business method call.
  3. It is safe to have "write-once" values stored in instance variables, i.e. values that are initialized once, and never change thereafter. The InitialContext and environmental variables are often handled this way.

    Any of the three methods you mentioned, all are safe places to initialize these values, but setSessionContext() seems to be the most common choice.
  4. Any of the three methods you mentioned, all are safe places to initialize these values, but setSessionContext() seems to be the most common choice.

    I just wondered if the setSessionContext() method is called by the container each time the SessionBean is "reused" and thus an instance variable would be newly constructed again and again.
    Anyway, I think I'll try out the constructor as it seems to be the only way to ensure that such an instance variable is really constructed only once.

    regards

    sebastian