13 October 2009

An example on pooling in Stateless Session Beans

Stateless Session Beans are pooled and reused by the container, also one important thing to note when you JNDI a statless bean to get a reference to the bean, subsequent calls to methods on this reference doesn't grantee to be for the same instance created for you from JNDI.
As the container can create new instances and handle them to you when necessary.

Here's the example that illustrate what I am saying:

The Stateless Bean implementation:

@Stateless
public class TestSessionBeansBoolingBean implements TestSessionBeansBooling {
Logger logger = Logger.getLogger(TestSessionBeansBoolingBean.class);
public void doSomeAction() {
// this action will take a long time:
try {
logger.info(">> Doing the business ");
Thread.sleep(5000);
}catch (Exception ex) {
ex.printStackTrace();
}
// Then I'll call this bean more than once, and I'll notice that more than once instances will be created
}
@PostConstruct
public void construct() {
logger.info("Creating a new Stateless Session Bean instance");
}
}

And Here's the Client, It is a standalone client :

public class TestSessionBeansBoolingClient {

public static void main(String[] args) {
TestSessionBeansBooling bean = (TestSessionBeansBooling) InitialContextHelper
.lookup("ejbinaction_part2/" + TestSessionBeansBoolingBean.class.getSimpleName() + "/remote");
bean.doSomeAction();
bean.doSomeAction(); // new bean instance will be created at this point
bean.doSomeAction();
}
}

And here's the output from one run for the client:

13:56:19,998 INFO [TestSessionBeansBoolingBean] Creating a new Stateless Session Bean instance
13:56:20,023 INFO [TestSessionBeansBoolingBean] >> Doing the business
13:56:25,062 INFO [TestSessionBeansBoolingBean] Creating a new Stateless Session Bean instance
13:56:25,062 INFO [TestSessionBeansBoolingBean] >> Doing the business
13:56:30,072 INFO [TestSessionBeansBoolingBean] >> Doing the business



Post a Comment