Harikrishnan
Harikrishnan

Reputation: 3802

Stateless bean not working

I wrote a stateless session bean. Then a business method which adds up the balance to an instance variable is also included. since it is a stateless bean it should not maintain the previous balance.

but it is maintaining it.

ie,

First I add 100 as balance, Again I added 100 as balance.

According to theory it should give 100 as the result since it does not maintains the state. But it is giving 200.

why?

I am using Netbeans IDE with Glassfish Server 3.0

Eg:


@Stateless
public class CalculatorBean implements CalculatorBeanRemote {
    double bal = 0.0;

    @Override
    public double Deposit(double parameter)
    {
        bal += parameter;
        return bal;
    }

} 

In Servlet, I added,

@EJB
private CalculatorBeanRemote calculatorBean;

and inside the service methode, out.println ("<br/><br/><br/>Deposit : " + calculatorBean.Deposit(100.0));

Upvotes: 2

Views: 281

Answers (1)

Aviram Segal
Aviram Segal

Reputation: 11120

You expect to get a different instance of the EJB but that's not always the case.

EJB are usually pooled, that means when you are done using an EJB it gets back to the pool and another call might get the same object.

The container does not clean your members so you get 200 and not 100.

You can use PostContrsuct and PreDestroy to setup and cleanup the EJB you are getting.

In general you should not use any members in a stateless bean (exactly because of what you are seeing)

Upvotes: 4

Related Questions