IBM Skip to main content
Search for:   within 
      Search help  
     IBM home  |  Products & services  |  Support & downloads   |  My account

developerWorks > Java technology
developerWorks
J2EE pathfinder: J2EE technologies for the stateful network
Discuss84KBe-mail it!
Contents:
Stateful application management
The Web tier
The business tier
Choosing the right technology
Conclusion
Resources
About the author
Rate this article
Related content:
The ABCs of EJBs
EJB best practices series
J2EE pathfinder series
Java design patterns 201
Subscriptions:
dW newsletters
dW Subscription
(CDs and downloads)
Best practices for choosing the right solution

Level: Intermediate

Kyle Gabhart (mailto:kyle@gabhart.com?cc=&subject=J2EE technologies for the stateful network)
Consultant, Gabhart Consulting
4 March 2003

Column iconBoth Java servlets and Enterprise JavaBeans components provide stateful server-side processing in J2EE. Each technology has its strengths and limitations, and each is better suited to some application setups than others. To help you choose the right solution for your enterprise, LearningPatterns Senior Mentor Kyle Gabhart compares the two technologies and evaluates their performance in some common stateful application scenarios.

In the first installment of the J2EE pathfinder series, we began an exploration of the current technologies for state management in J2EE. Last month, we discussed the best options for managing stateless networks in J2EE; this month we'll talk about the technologies for managing stateful ones.

I'll begin with a brief introduction to stateful application management, then talk about how different solutions can be applied to either the Web or the business tier. Next, I'll compare the strengths and weaknesses of J2EE's technologies for stateful application management. As in the previous installment, we'll close with a look at some of the most common implementations of each technology and some best practices for choosing the right solution for your enterprise.

Please note that for the purposes of this article, JSP (Java ServerPages) files are considered to be a specialized type of servlet.

Stateful application management
As you may recall from the previous installment, Web application protocols break down into two broad categories: stateless and stateful, and a protocol's state refers to its ability to "remember" information from one transmission to the next. Because stateful connectivity is one of the basic requirements of most enterprise applications, and because Web applications live and die by HTTP -- an inherently stateless protocol -- clever developers have come up with numerous tricks for simulating stateful connections over HTTP. Stateful information can be stored in HTML form fields, appended to hyperlinks, or stored in cookies on the client side.

Stateful interactions between client and server can be managed on either the Web tier or the business tier. To manage state on the Web tier, we use servlets combined with the HTTPSession API. To manage state on the business tier, we use stateful session EJB components. We'll explore both development options in the sections that follow.

The Web tier
The Servlet architecture's HTTPSession API lets application developers manage the state of client-server interactions (or sessions) across the network. The HTTPSession interface defines the core functionality for the HTTPSession API. It provides a way for J2EE applications to identify an individual client across more than one page request and to store data on the server that is associated with that client. Through this interface, the servlet container creates and manages a session between the client and the server. This session is represented by an HTTPSession object, which persists for a specified period of time across multiple connections and page requests from the same client. Servlets use this interface to view and manipulate information about a session, such as the creation time and the last time the session was accessed. The interface also allows servlets to bind objects to sessions, thus associating that information with the specified client in a way that persists across multiple connections by the same client.

The Servlet architecture

The Servlet architecture is unchanged by the use of the API. Just as in a stateless network, servlets fulfill business requests on behalf of clients and serve as controllers, views, or both. Servlets also do an effective job of handling user interactions such as content formatting and display, basic request processing, security requests, and more. As in a stateless network, servlets are best used to manage client interaction, so helper classes such as JavaBeans are often used to handle the heavy processing or interface with back-end components.

So, the HTTPSession interface allows the servlet container to create and manage client sessions and enables servlets to access session-related information, bind objects to the session, and access previously bound objects. So far so good. But how does the servlet container track clients that are communicating over a stateless protocol such as HTTP? To accomplish this, each HTTPSession object is given a unique ID to ensure that each client's session and session-related data can be uniquely identified. Given the inherently stateless nature of HTTP, this session ID must be passed by the client to the server upon each request, in order for the servlet container to associate a client with the correct session. The session ID can be passed in one of three ways: as a parameter in an HTML form (typically a hidden field); as a parameter appended to the query string; or as an attribute of a cookie. Regardless of how the session ID is passed, the servlet container will intercept it, look it up, and find the HTTPSession object associated with it.

Servlet performance
The lightweight threading model created by the Servlet architecture is in no way compromised by a servlet or JSP file creating, reading, or modifying an HTTPSession object. The object is simply a hashtable or similar collection that stores object references as simple key-value pairs. Likewise, the implementation of the HTTPSession memory space itself is lightweight, requiring no more than the storage (perhaps serialization) of the session object and the corresponding session ID. In short, servlets can support stateful interaction with HTTP clients with a minimal impact on the application design or container resources.

The business tier
J2EE provides built-in support for handling state on the business tier. Like stateless session beans, stateful session beans are mapped to business processes. The key difference between the two is that, whereas stateless beans and their data live for the lifetime of a single client request, stateful beans maintain a conversation with the client and their data persists across multiple requests. Unlike servlets, stateful session beans do not require any special objects or the use of an additional interface to create stateful connections. The EJB container provides for all stateful session bean management. All that is necessary is for the bean to be declared as stateful in its deployment descriptor.

The EJB architecture

From an architectural standpoint, stateful session beans are no different from their stateless counterparts. Both types of beans can serve equally well as views, controllers, or model; both often implement the Facade pattern or the Business Delegate pattern; and both work with multiple client types. Stateful session beans can be accessed by a servlet (or JSP file), a JavaBean helping a servlet (or JSP file), another enterprise bean, or directly through an applet, Swing app, or other Java application, or even a non-Java client using the IIOP protocol.

Managing stateful beans
As previously explained, session beans are the most lightweight type of enterprise bean. Stateless session beans in particular can be easily pooled by the container, because they only need to maintain state per request.

Stateful session beans, on the other hand, are not as friendly with the container's resources. A pool of stateful session beans cannot be used to accommodate any client request the way that a pool of stateless EJB components can. A stateful bean can only handle requests from a single client until the client releases its hold on that particular bean instance. Stateful session beans consume a substantial amount of the container's time and memory.To preserve the bean's state between client calls, the container must either keep the bean instance in active memory or temporarily write the state to a persistent store such as a filesystem or database. Allocating the state to a persistent store is known as passivation. When a previously passivated enterprise bean is requested again, the container will activate it by retrieving a bean from the pool and initializing it with the persisted state of the bean prior to passivation. The diagram below illustrates the passivation and activation of stateful session beans:

Figure 1. Passivation/activation of stateful session beans
Diagram of the passivation/activation of stateful session beans

It is up to individual vendors to determine whether beans will be left in memory or passivated and then later activated. While the passivation mechanism is helpful in freeing up container resources, it does nothing to prevent a server crash from losing the active state of a stateful session bean. Although some vendors provide a session recovery feature to account for this, it is not standard, so reliance on this feature can reduce application portability. Fear not, however! The EJB specification does define an interface (javax.ejb.SessionSynchronization) that alerts enterprise beans to the status of a transaction, including a failed transaction due to server crash (assuming someone didn't just pull the plug on the server). Enterprise beans that implement the SessionSynchronization interface must define the three declared method signatures: afterBegin(), beforeCompletion(), and afterCompletion(boolean). These methods open the bean to receiving three additional callbacks from the container to allow the proper handling of transaction state within the bean.

EJB component performance
From a performance standpoint, servlets and stateless session beans are fairly competitive technologies. They are both able to use an instance pool to service requests from. When you add in the management of application state, however, a substantial performance gap becomes apparent. Unlike the lightweight HTTPSession mechanism available as part of the Servlet architecture, stateful session beans require a much more heavyweight solution to state management such as the passivation/activation scenario outlined above. This common solution to stateful session beans requires server time and resources for passivating the bean state, recycling bean instances, and activating a bean state. Each of these processes can require several container calls, as well as callback methods made directly on the bean to be sure that the bean state is handled properly. All in all, stateful session EJB components provide a heavyweight mechanism for managing application state.

Choosing the right technology
Unlike a stateless J2EE architecture, J2EE applications do not offer typical configurations to serve as a guide or blueprint. When it comes to managing state, the appropriate architecture depends on the following factors:

  • Is the client Web-based (HTTP)?
  • Does the conversational state need to be incorporated into a GUI?
  • What kind of load conditions will the server be under?
  • Does the stateful component need to be able to survive a server crash?
  • What sort of transactional context is required for this component?
  • How substantial is the stateful data?

Although some of the above questions seem to clearly lean to one technology over the other, many stateful scenarios actually call for the use of both servlets and EJB components. The crucial determination is whether state should be managed on the Web tier, the business tier, or both. In the next section, we'll look at some possible enterprise application scenarios and their most fitting solutions.

Application client
A standard application client is one that interfaces with another system or component. We'll look at three typical application client scenarios and discuss the most appropriate stateful solution for each one:

  • If the client is Java-based and behind the same firewall as the server, you'll want to first determine whether a stateful interaction model is necessary. Managing stateful session beans is resource-intensive, so you will want to consider more lightweight alternatives. The best solution is to use RMI to talk directly to stateless session beans in the application server. If a stateful solution is essential, consider using stateless session beans with a simple transaction layer, or creating a thin servlet layer on top of the business tier. Either solution would provide a stateful experience at a fraction of the cost. In the end, if your client must be tightly-coupled with the state of the business process across multiple requests, and the addition of a Web layer is unacceptable, then stateful session beans are the clear choice.

  • If you're working with a non-Java client or a client that is not behind the server's firewall, the issue of state management is a bit different. In this scenario, you want to start by identifying the goal of state management. If the goal is to provide a fluid experience for a user through some type of GUI, then you can manage the state on the Web tier. If the goal is to tie together a complicated business process across multiple requests, then state management should reside on the business tier. Again, you should always explore other options such as the use of a stateless session bean with a transaction layer.

  • Some application server vendors have exposed their EJB container in such a way as to accept native IIOP invocations, allowing CORBA clients to treat EJB components as native CORBA applications. This allows a non-Java client to use the IIOP protocol for communicating with stateless session beans. In this setup, the client bypasses the Web tier and communicates directly with the business tier (session beans) using the IIOP protocol. At this point, the architectural analysis is identical to that of a Java-based application behind the firewall. Refer to the first scenario to understand the issues of state management on the business tier.

An e-business on demand environment
As we discussed last month, stateless session beans are well designed for e-business on demand applications. They are very lightweight and can be easily pooled to ensure excellent scalability. Stateful session beans, on the other hand, are not well designed for such applications. State management is often needed within e-business on demand applications, but it is best handled by a proprietary mechanism or through J2EE transactions. Another possibility is to invoke an EJB component as though it were a CORBA component. This option is especially useful when one or more of the applications to be integrated are CORBA components.

Rich GUI client
There are three essential rich GUI (not HTML, not command line) client types: Java applets, stand-alone applications, and Java Web Start. The following solutions are applicable to any of these three rich GUI component types:

  • If your client and server are separated by a firewall, you'll want to have your client communicate directly with a servlet through HTTP. The servlet tier can handle simple business processing using helper classes. If your application has more complex requirements or higher request frequency involving enterprise resources, you'll want to use session beans to handle the business processes. Here, once again, you should consider the necessity of a stateful interaction model as part of your decision process.

  • If your client and server are behind the same firewall, a straight RMI invocation is likely your best bet. In this case servlets simply represent additional overhead and unnecessary architectural complexity. In the case of an applet or Java Web Start, a servlet could initiate the transaction by serving the first HTML document with an applet or Java Web Start application link. From there, it would be best to have the client establish a direct RMI connection with one or more session beans. The setup for this scenario is the same as it would be for a typical application client scenario that is not behind the same firewall.

If you're working with a native-GUI client and have the need to manage a complicated transaction or series of transactions, you'll want to once again consider invoking an EJB component as though it were a CORBA component. If that is not an option, you can always have the client communicate with a servlet through HTTP and manage the session accordingly.

Web application
In the case of a standard, Web-based application, it doesn't matter what side of the firewall the client is on; the use of servlets is imperative. Because you'll be using HTTP as the transport protocol, you will be working on the Web tier. The only real decision -- whether or not to use EJB components behind the scenes -- will be based on the relative need for EJB container services. First you will select the general component types (such as servlets and session beans). Next, you'll choose some more specific types that match the application's requirements for user interface display and business request processing (such as JSP pages and stateful session beans). As far as state management is concerned, similar issues exist for Web applications as for other client types. Some standard questions (and answers) will help you determine the right state management solution for your Web application:

  • Does the stateful experience need to be tied directly into the user interface? If so, state must be managed with servlets and the HTTPSession API.

  • Does your business process need to span multiple calls from the client? If so, you have three options:
    1. Use a stateful session bean to provide a stateful business process.

    2. Use stateless session beans and have the persistent data cached on the server. A reference to the cache can then be stored in an HTTPSession object for the client.

    3. Have a JavaBean serve as a business delegate (see Resources) by calling methods on the bean, having the bean batch all the data from the client, and contacting the stateless session EJB components only when the client is ready to commit the business process. The HTTPSession API is again used to persist the JavaBean instance.
  • Does your stateful business process need to be failsafe? If so, you have three options:
    1. Use an application server that provides automatic support for recovery of stateful session bean state.

    2. The SessionSycnhronization interface allows stateless or stateful session beans to respond to transaction failures. This would allow you to rollback a transaction, persist data, or perform any other cleanup functions you might need. Many times, a server failure will not prevent the container from invoking the callback methods declared by the interface.

    3. Many Web servers provide a failsafe HTTPSession implementation. If your server does this, you can use a JavaBean as a business delegate.

Multiple client types
The final scenario calls for a combination of client types, such as a Web-based browser and a standard rich-GUI desktop. In this case the stateful options are no different from the stateless ones. Refer to the first article in this series for details.

Conclusion
In this second installment of the J2EE Pathfinder series, we've explored the relative strengths and weaknesses of using Java servlets and stateful session beans to fulfill client requests and provide a stateful experience. The scenarios discussed here don't cover every situation, but they are representative of some of the most common uses for servlets and session EJB components in a stateful communication context.

In our next installment, we'll begin a two-part exploration of persistent data management, starting with a comparison of entity beans and JDBC. Until then, happy pathfinding!

Resources

  • Participate in the discussion forum on this article. (You can also click Discuss at the top or bottom of the article to access the forum.)

  • See the complete developerWorks J2EE pathfinder series by Kyle Gabhart.

  • If you are a newcomer to EJB technology, you may want to check out the sidebar in the first article of this series, "The ABCs of EJBs."

  • The J2EE home page is the place to start if you want to learn more about the Java 2 platform, Enterprise Edition and related technologies.

  • Brett McLaughlin's EJB best practices series (developerWorks) introduces some of the basic patterns and uses associated with Enterprise JavaBeans components.

  • Learn more about the Facade, Business Delegate, and Factory patterns mentioned in this article. See Sun Microsystems's Java BluePrints.

  • Paul Monday's excellent "Java design patterns 201" tutorial (developerWorks, April 2002) offers a more theoretical discussion of the use of design patterns in Java programming.

  • You'll find hundreds of articles about every aspect of Java programming in the developerWorks Java technology zone.

  • Also see the developerWorks Java technology tutorials page for a complete listing of free tutorials on Java technology.

About the author
Photo of Kyle Gabhart Kyle Gabhart is an independent consultant and subject matter expert with J2EE, XML, and Web services technologies. Kyle is a popular public speaker, recognized for his enthusiasm and dynamic analysis and presentation of emerging technologies. For information on his recent and upcoming presentations or industry publications, visit Gabhart.com. Kyle can be reached at kyle@gabhart.com.


Discuss84KBe-mail it!

What do you think of this document?
Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)

Send us your comments or click Discuss to share your comments with others.



developerWorks > Java technology
developerWorks
  About IBM  |  Privacy  |  Terms of use  |  Contact