Question

I'm new in EJB. I heard that in some cases it is acceptable to store some information (such as configurations) in stateless beans. As I understand the stateless bean lifecycle begin on bean's method invocation and end on method conclusion. After method ends up the stateless bean will be returned to the pool.

  1. I want to know if config field will be reinitialize each time when the bean's method is invoked or only on bean creation.
  2. Also I want to know what else information it is acceptable to store in stateless bean private fields.
@Stateless
public class MyBean {

    private String config = ....;

    //.....
}

Thank you in advance.

Was it helpful?

Solution

  1. The private String config = ... will be ininialized only once for every instance of a bean, when it is created (usually during application startup, but also possible when the application server decides that more beans are needed to handle growing traffic).

  2. Basically, when you execute a public bean's method, you're guaranteed to be the sole executor of that bean instance. During that time you're allowed to store anything in private variables. Once you return to the code that called your bean, though, you're never guaranteed that subsequent calls will be directed to the same instance.

Example:

@Stateless
public class MyBean implements MyBeanIntf {

    private Object state;

    @Override 
    public void beanMethod() {
        state = new Object();
        privateMethod();
    }

    private void privateMethod() {
        // it's safe to access 'state' here, will be the one set in
        // beanMethod()
    }

    @Override
    public void otherMethod() {

    }
}

@Stateless
public void MyBeanClient {
    @EJB
    private MyBean myBean;

    someMethod() {
        myBean.beanMethod();
        // Not necessarily the same instance that executed beanMethod
        // will execute otherMethod
        myBean.otherMethod(); 
    }
}

That's theory. In practice, I'd avoid code that relies on keeping internal temporary state in a stateless EJB -- just because this style suggest to other programmers that it's OK to have state of an SLSB in general, which leads to confusing code and potential errors (esp. if state from previous executions is mistakenly picked up as the current one).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top