Best Practices for Session Beans


The following sections describe some of the best practices to keep in mind while coding stateless and stateful session beans.

Optimizing JNDI Lookups

Because the Java Naming and Directory Interface (JNDI) lookup can be an expensive operation, caching all the onetime initialization procedures in the session bean's setSessionContext() method is the recommended practice. The EJB container calls the session bean's setSessionContext() to associate a session bean instance with its context maintained by the container. Typically, a session bean instance retains its session context as part of its conversational state. In addition, setSessionContext() is called in an unspecified transactional context, so there is no transaction overhead. This method is called only once during the bean's life cycle.

For example, if you are making some database calls from a stateless session bean, look up the datasource, as shown in Listing 23.1.

Listing 23.1 Database Calls from a Stateless Session Bean
 public class TraderBean extends SessionBean {            public Context = null;            public DataSource = null;          public void setSessionContext(SessionContext sc) {             ctx = new InitialContext();               ds  = (javax.sql.DataSource) ctx.lookup("MyDataSource");         //This reference can be used until the bean instance is destroyed            }     } 

For stateful session beans, it is essential to do this initialization work in the ejbActivate() method and release the resources in the ejbPassivate() method. As far as stateless Session beans are concerned , the ejbActivate() and ejbPassivate() methods are not called since there is no conversational state to passivate.

Similarly, you can cache Java Messaging Service (JMS) connection factories and home and remote stubs for other beans. This optimization might not be a big win when very few clients access your bean; however, you can see the performance advantage when load-testing your application with a large client base.

When Not to Use Stateful Session Beans

Stateful session beans represent a conversational state between a single client and a bean instance. Stateful session beans cannot be shared between multiple users and should not be modeled as a shared cache or any shared resource.

Tip

If multiple clients need to access a single EJB instance, entity beans are the best choice.


Because each client requires its own stateful session bean instance, the number of bean instances and the associated resource requirements can grow quickly. As these resources grow, the EJB container will use passivation techniques to manage its idle resources; passivation is an expensive operation.

Some enterprise applications can take advantage of the stateless programming model, allowing the stateless session bean to leverage efficient pooling techniques implemented within the EJB container of WebLogic Server. In general, stateless session beans are much easier to scale than stateful session beans.

Also, clients of stateful session beans should always call the remove() method after finishing with a stateful session bean instance so that the EJB container can release resources as soon as possible. If you do not call the remove() method on stateful session beans, the EJB container eventually passivates the bean, but this process involves extra disk access, which is not a good practice for high-volume sites.

Stateful session bean writers must also be careful when integrating stateful session beans with Web applications. In practice, it can be difficult to use stateful session beans correctly in servlets or JavaServer Pages (JSPs). If a stateful session bean is used within the scope of a single request, then multiple threads do not use that instance.

However, Web applications often store the reference to a stateful Session bean within the JSP's session scope. This can be problematic as it can cause the session bean instance to be accessed concurrently. One common scenario is when a user enters a Web site, creates a new HTTP session, which in turn creates a stateful session bean instance, and invokes some business methods on this stateful session bean instance. If the user clicks on the stop or reload button while a stateful session bean is processing a request, the end-user (client) will end up accessing the same bean instance resulting in a concurrent call. For this reason the EJB specification prohibits concurrent access to stateful session beans.

Making loopback calls while coding stateful session beans is also illegal, as shown in this example:

method-A in Bean-A calls method-B in Bean-B calls method-A in Bean-A

There are three possible solutions to this problem:

  • Use stateful session beans within the scope of a single request. Although this method is possible for complex requests , creating a new stateful session bean instance for every HTTP request introduces extra overhead.

  • Set <allow-concurrent-calls> to true in the WebLogic deployment descriptor. When this option is true, the EJB container blocks concurrent method calls and only allows a method call to proceed once the previous call has finished.

  • Use entity beans or HTTP servlet sessions for applications that need to store data between requests.

Scalability Issues with Stateful Session Beans

Unlike stateless session beans, the container does not maintain a pool of instances to multiplex on client calls. Each client has a unique stateful session bean instance. For a large Web site, the number of clients might be in the thousands, so storing all these instances in memory for the client's lifetime is not always feasible . To support large numbers of clients and effectively manage resources, the EJB container manages its working set by temporarily transferring the state of an idle stateful session bean instance to disk. Because this process involves the passivation of information to disk, you should be careful when modeling applications with stateful Session beans.

The SessionSynchronization Interface

Stateful session beans with container-managed transactions can optionally implement the javax.ejb.SessionSynchronization interface. This interface contains three methods:

  • afterBegin()

  • beforeCompletion()

  • afterCompletion(boolean)

The container calls the afterBegin() method when the stateful session bean enters a transaction. The beforeCompletion call occurs before the transaction is prepared to commit. The afterCompletion callback accepts the boolean argument. If the container passes true to afterCompletion , the transaction was committed; false indicates the transaction was rolled back.

The beforeCompletion method is often used to perform final transaction processing so that it may be committed with the rest of the transaction. Because the afterCompletion method is called after the transaction is committed or rolled back, the bean developer can add logic to set the cached information to a known state. This is especially true in the case of a rollback where the state of the bean instance might no longer be valid. The afterBegin method can be used in circumstances where internal variables need to be set and used only by transactional code, or possibly to trigger the execution of transactional code.

Session Beans As a Facade to Entity Beans

Enterprise JavaBeans are generally divided into three core types of beans: session beans, message-driven beans, and entity beans. Beans can also be categorized as those that act as business objects and those that act as data objects. Session beans and message-driven beans are business objects; entity beans are data objects. In most applications, business objects are exposed to the Web tier, because business objects can use data objects to deal with data stores. Nevertheless, in some cases, it is necessary to allow users to directly access and manipulate data objects, which means exposing entity beans to the Web tier . This can leave your application open to security threats and can result in poor performance due to the remote nature of Entity beans.

Fortunately, there is a design pattern that allows you to enable user access to data objects without exposing your entity beans to the Web tier. The Session Facade pattern places a session bean between the entity bean and application clients. The Session bean can be thought of as managing access to multiple Entity beans, thus reducing exposure to the client and reducing the number of remote calls made to the Entity beans.

Generally, Session beans are designed to act as an interface between the business tier and the persistent tier. The primary use of a Session bean is to manage data validation, security, and general business-specific functionality. However, by wrapping Entity beans within the fa §ade of a session bean, you can carry out the processing of business rules without tightly coupling Session bean functionality with your Entity bean code. Hence, the stateless Session bean is responsible for starting transactions and committing or rolling back transactions before returning to the Web tier. This approach of using session beans ensures that the resulting transactions are short and encompass only transactional logic.



BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net