Wednesday, August 27, 2008

Write code for the bean classes of Stateful and Stateless Session Beans SCBCD Exam Objective

Write code for the bean classes of Stateful and Stateless Session Beans.

The new EJB 3.0 specification makes developing and designing enterprise components easier and simpler than ever.

The best place to start designing EJBs is with Session beans. There’s really three types of EJBs: Session Beans, Entity Beans and Message Driven beans. Entity Beans save data to a persistence store, such as a database. Message driven beans read messages off of a queue or topic. Session beans? Well, they’re the EJBs that aren’t Entity Beans or Message Driven Beans. J

A tongue in cheek definition for sure, but it’s not all that far from the truth. If you have an enterprise component, something that might need to be invoked by remote clients, might have concurrency issues under a heavy load, or simply needs the server side, enterprise scalability that deployment to an EJB container provides, while of course, not being an entity bean or a message driven bean, well, that’s a Session EJB.

Session Beans can be divided into one of two categories: Stateful Session Beans (SFSBs) or Stateless Session Beans (SLSB). I always liked calling them American Beans, or Canadian Beans, because America has lots of States, and Canada doesn’t have any (it has provinces), but that naming convention never really caught on, so SLSB and SFSL will remain the accepted nomenclature for the timebeing. Basically, Stateful Session beans maintain a conversational state with the client, and Stateful Session Beans don’t. A more Java centric definition might be to say that Statefule Session beans have meaningful instance variables that are associated with a given client, whereas Stateless Session beans do not. Of course, I could try and describe the differences between Stateful Session Beans and StatelessSession Beans using big words and descriptive definitions, but in my world, a good example is always the better way to go.

Take a look at this Java class. It’s simply a home-made Timer. It can stop, it can start, and once it’s been started, it can tell you how much time has elapsed since starting it. It’s not going to win anyone a programmer of the year title, but it’s a good class, it’s a simple class, and it will be absolutely perfect for exploring Session beans, and the subtle distinction between a Stateful Session Bean and a Stateless Session Bean.

Take a look at the following Java class:

package com.mcnz;

public class Timer {

private long startTime;
public Timer() {}

public void start(){
startTime = System.currentTimeMillis();
public long getStartTime() {
return startTime;
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
public boolean isStarted() {
if (startTime == 0 ){return false;}
else {return true;}

It’s a Timer, as you could probably gather from the name of the class. It’s a simple class, with one instance variable of type long that keeps track of when the Timer is started, it has a default constructor that doesn’t really do anything other than look pretty, it has a getter method for the startTime instance variable, and it has a little getElapsedTime method that tells you how long it has been since the timer was started. Oh yeah, and I just threw in a little isStarted method that can tell you whether the timer has been started or not. Basically, if the instance variable has a value of zero, the Timer hasn’t been started.

I like this little class because it’s simple and stratight forward, conceptually it’s fairly easy to comprehend, and from a Java standpoint, it combines a good mix method signatures, with one returning a Boolean, two returning longs, a void method, and even a cute little default constructor. This is a great little class with which to work.

I’m just going to throw this little Timer class into a runnable class named TimerTester. It’s just going to iterate through a loop a bunch of times and print out how long it took to iterate through the loop – it’s all, simple, Introudction to Java type of stuff:

package com.mcnz;

public class TimerTester {

public static void main(String[] args) {
Timer t = new Timer();

for (int i = 0; i<100; i++){
System.out.print("\nTotal Time: " + t.getElapsedTime());

When I run this program, get output that looks something like this:

Total Time: 20

Man, those IBM Thinkpads are fast! 100 iterations only took about 20 milliseconds. J

Unfortunately, all of the time spent on the Timer class and the TimerTester hasn’t advanced our knowledge of Enterprise Java programming one, little, iota. Everything we’ve done so far leverages nothing more than the Standard Java Development ToolKit (SDK), and you certainly don’t need the facilities of an EJB container to run this code. This code could run on any computer that has a standard, Java Runtime Environment installed.


Let’s just say that our Timer was becoming extremely popular. And not only was it popular, but its services were being required by a large number of applications, not only for logging, but for monitoring, performance, and basic information feedback about how applications were running. Furthermore, perhaps many applications were needing the technical facilities provided by the Timer class, many different types of applications were using the Timer, from stand-alone Java applications, to Servlets, JSPs, and potentially, even other EJBs. And let’s also say that we wanted to optimize our hardware utilization, so instead of wasting clock cycles on stand-alone client machines, or other web servers or Servlet engines, we wanted to run the Timer class on high performance, dedicated server hardware that would redue the client load and make scalability and concurrency much easier to manage. Well, if that was the case, we’d want to throw away the Timer class that runs in a stand-alone mode in a single Java Runtime Environment (JRE), and instead, morph our existing Timer class into a exceptionally talented Enterprise Java Bean.

So, how would our Timer morph into an EJB? Well, first of all, it doesn’t map to a database table, and it doesn’t read any data from a Queue, so it’s not an Entity Bean or a Message Driven Bean. Our Timer is definitely a Session Bean EJB candidate. And of course, Session Beans can fall into one of two categories: Stateful Session Beans or Stateless Session Beans, and since our Timer class does have an instance variable, the startTime of type long, and since the instance variable can take on different values depending on which client is invoking it, we have to conclude that our Timer class would best fit into the mold of a Stateful Session EJB.

So, how does a normal, innocuous, simple JavaBean transition itself into an Enterprise Java Bean? Well, it’s amazingly simple, especially with EJB 3.0.

For me, the toughest part of turning my Timer class into an EJB is changing the name of the Timer class to StatefulTimerBean, and a corresponding change of the constructor from Timer() to StatefulTimerBean(). A quick change of the package name from com.mcnz to com.mcnz.ejb is another little razzle-dazzle change that I’ve made. Also, you’ll notice the added import statement bringing in javax.ejb.*;

No comments: