This article published with permission of SIGs publications. Original date of publication May 1998. These version does not exactly correspond to the printed version due to modifications after submission.

Enterprise Java Beans

By: Dave Orchard

The Enterprise Java Beans (EJB) specification has been released, to the enthusiastic support of server vendors and software developers everywhere. EJB is the next logical step in Java's multi-pronged evolution. For the past year, Java has evolved into the language of choice for server developers. Hardly a day goes by without a company announcing new features for Java server development, or the deployment of an application relying upon Java on the server.

This article will summarize the EJB specification without being a simple rewording of the excellent documentation available at the JavaSoft site. Some of the benefits and potential problems of EJB will be discussed, as well as a description of some important architectural decisions that EJB allows. Finally, some thoughts on integration of EJB with the Web are offered.

EJB extends Java's Write Once, Run Anywhere (WORA) promise of hardware and OS independence to middleware and application server independence. EJB means that developers are not locked in to using a particular vendor's middleware servers. This offers developers the hope that they will be able to concentrate on producing more business logic - that is the coding of a business' rules, logic and knowledge - rather than spending much of their time focusing on "plumbing".

The underlying vision of EJB is that the specification of services - such as naming, persistence, transactions, and security - will disappear from the realm of competition between vendors. No longer will the vendors compete upon the specification of basic services. Vendors will compete on development, deployment and administration tools, connections to back-ends, integration with web servers, and class library offerings. Developers will create re-usable business objects, deployable across any hardware, operating system or middleware.

 

The Delivery

By the time you are reading this, the EJB specification will be released and at version 1.0. It was developed by JavaSoft, along with a great deal of input from third parties. It defines a framework for vendors and clients to work in. Javasoft has committed to providing a reference implementation, similar to the reference implementations of HotJava, Java Server and the JDK. Almost all the middleware players have pledged support, ranging from the new breed of application servers to the traditional server heavyweights - from Bluestone, NetDynamics, WebLogic and Netscape to Sybase, BEA, Oracle and IBM.

EJB is an extension of the Java Beans architecture to the now-standard three-tier architecture. Specifically, EJB defines a set of services and APIs for server-side Java components. The advantages of three-tier architectures are familiar to most readers, but I'll try to provide the world's shortest summary of the advantages. The main advantages are: scalability of number of clients and servers, increased perceived client performance, integration with existing web architectures, increased ease of deployment to clients and servers, increased server reliability, and increased adaptability of servers to varying clients. EJB fills the need for definition of run-time and design-time environments for the server-side of three-tier architectures.

The Benefits

The benefits to EJB vendors are straightforward - developers are requiring EJB support. Products supporting EJB have a considerable advantage over products without EJB support. EJB vendors also benefit indirectly by a large EJB server market, as a large market of EJB products leads to a increased revenue from every participant. So rather than fighting over how to split up the server-side market, cooperation on EJB means that the server-side market will grow very quickly. Additionally, a large number of EJB vendors are creating EJB servers to provide a standard migration path for the vendor's existing products. Thus the vendor's current customers will not feel a need to replace the installed products. An example of this the Component Broker (CB) middleware product from IBM. Existing DB/2, CICS, and IMS installations will be able to keep their systems, and layer CB on top of them. The two principal advantages for vendors are new markets and the retention of current markets.

Developers are supporting EJB because they can focus on the development of business logic separate from the intricacies of the object plumbing. The separation of business logic from plumbing is perhaps the largest benefit of EJB. Current estimates indicate that 40% of the time spent on application development is devoted to plumbing issues.

Developers are also hoping that EJB will promote reuse. One of the major reasons that business objects have not been reusable is because they have been contaminated with service knowledge. For example, a student business object that contains service information, such as how it is stored in a database, error handling, debugging information, etc., is difficult to move to a different application where the underlying service assumptions have changed. Eventually, EJB will lead to a higher level of design and code reuse.

Developers are supporting EJB because they can deliver components and applications for a reduced cost, with an increased time to market, and an increased market size, and increased reliability.

The Framework specification

After all the hand-waving about benefits, what really is EJB? EJB is a specification for what developers and vendors must provide at design-time and run-time. The most significant facet of the specification is the new container model. The container provides mechanisms for a java bean to define how the container is to treat it, in effect the services that the bean requires of the container. The services that the container provides for the bean are many: naming, life-cycle, persistence, transactions, messaging, security and packaging. This article will look at each of the services in detail shortly.

EJB has two primary extensions to Java: a container model, and a complex specification of services. The container model is a standard design pattern, used in many frameworks including Microsoft's COM. The power of EJB is in the specification of services and the implementation of the services in the containers. Objects can stay simple, because they gain service by cooperating with the container for the services. The previous models, CORBA and COM, required that objects grow to add behaviour. On the server, this led to very large objects, completely bound to services. The objects are difficult to program and almost impossible to widely re-use.

EJB will be the first widely adopted framework for server-side containers. The server object fits into the framework by specifying the services it needs. At deployment time, the framework introspects the installed server objects for the run-time service rules. At run-time, the framework intercepts all client communication with the object. The framework wraps the server object with specified service functionality, commonly persistence and transactions. The framework delegates the method calls to the server object when it is appropriate.

Vendors will provide an EJB Server, tools for creating and installing containers, tools for installing the enterprise bean, and run-time support for the services required by the container and it's bean. The runtime environment for EJB server objects is within an EJB server and the generated EJB containers. The EJB server provides the home for all the EJB containers. It allocates system resources to the various containers. The EJB container is responsible for the services that the Bean requires - persistence, transactions, naming, security and life-cycle management. There is one container for every enterprise bean class. The container will typically be created by the vendor's tools, using the enterprise bean specification as the input.

The container wraps/intercepts all method calls to an enterprise bean. It makes use of any services need before and after the method invocation. A typical example of this is the persistence service. When a client invokes a method on a server object, the framework:

  1. instantiates the object in memory - perhaps resurrecting from a relational database
  2. invokes the method on the object, and
  3. optionally stores the object to the database after the invocation is complete

Persistence

Speaking of persistence, EJB supports the two object persistence modes - transient or persistent. EJB defines them as session and entity beans respectively. Entity beans are defined to have a persistent primary key, and the bean is stored in a persistent data store. Interestingly, session beans can be stateful or stateless. Stateful session bean are stored persistently, but they are not addressable by a primary key. The use of a primary key is the differentiator between session and entity beans.

Session beans are meant for temporary copies of data, optionally stored in a persistent data store. Session beans are required for EJB version 1.0. The session bean does actions on behalf of a client request, often accessing persistent data. The session bean is not shared between client requests. The session bean is responsible for storing it's state to a data store. Session beans are optionally transactional.

Entity beans are defined to be objects reflecting some state in a persistent store. Entity beans are optional in EJB 1.0, but mandatory for EJB 2.0. The entity bean state exists outside the lifetime of client requests. The entity bean state is shared between client requests. The entity bean state can be managed by the entity bean, or it can be delegated to the container. Entity beans are transactional.

The choice of session or entity beans is made by the EJB developer by inheriting from either EntityBean or SessionBean. The developer then optionally implements various functions. For example, a stateful session bean that has open files must close the files when the bean is being stored to a persistent store. The bean developer provides an implementation of the ejbPassivate method to do any special cleanup before passivation.

Often sessions are equated with stateless business objects, and entities are equated with stateful business objects. That comparison is not completely valid. Stateful and stateless middle-tiers both acknowledge that the data in the middle-tier is representative of data in the persistent storage. The key difference between the stateful and stateless is whether the state is shared between clients or not. A stateless middle-tier will create a copy of the state for every client request, whereas a stateful middle-tier will use only one copy of the state. A stateless middle-tier could easily consist of entity beans that are activated for each client, then passivated immediately after the client request is serviced.

The debate between stateful or stateless middle-tiers is widespread. In general, database and integration product vendors are supporting stateful middle-tiers, examples being IBM and Oracle. Stateless middle-tiers are advocated by many in the web community, prominent gurus such as Roger Sessions, and by Microsoft.

As usual when there are two entrenched sides, they are both right, as it depends on the type of application. The choice of stateful or stateless objects is one of the largest decisions that system architects will make in application development. The important factors in the state decision are:

I'm leery about making architectural recommendations, but I'll venture the following thoughts. Stateless objects beans are often appropriate for Web applications, applications that do not have sole access to the data store, or applications where the bean state must be shared across CPUs - possibly for load-balancing or fault-tolerance.

Other Services

Enterprise Java Beans are named using the Java Naming and Directory (JNDI) API. The naming hierarchy has the EJBS at the top level, layered on the application name, then the container name. The bean is identified by a primary key within the container. There are no naming convention requirements for the primary keys. In addition, CORBA Naming standard (COS) is supported. An EJB Server that supports COS will automatically publish a COS version of the EJB name.

The Container provides the life-cycle services of an object. All containers have a Home interface that provides Factory methods for creation of objects. Entity beans also have a set of Finder methods for retrieving objects based upon a primary key. Home interfaces have destroy methods for deleting objects.

EJB provides an infrastructure for distributed transactions using two-phase commit protocols. It is based upon the OMG Transaction Service (OTS), specifically the Java Transaction Service(JTS) implementation of OTS. JTS supports multiple transaction managers propagating transactions to multiple databases. One of the exciting aspects of EJB is that it brings the strength of database transactions to objects. Distributed objects can participate in the begin/prepare/commit sequence typical of transaction protocols.

The transaction requirements that a bean supports are specified in the transaction attribute associated with the bean. The options are BEAN_MANAGED, NOT_SUPPORTED, SUPPORTS, REQUIRES, REQUIRES_NEW and MANDATORY. These options correspond to the level of transaction support that a bean can operate in or that it requires from the container. Readers unfamiliar with transactions and two-phase commit protocols are encouraged to investigate transaction theory as it can significantly improve the robustness and integrity of data and programs.

EJB can use supports CORBA and RMI for messaging. The beans are defined using the RMI interfaces, then the standard RMI deployment is used. EJB Servers can also support CORBA IIOP integration. The EJB server provides a CORBA ORB and tools for creating a CORBA object from the EJB object. It is also possible to support DCOM and COM this way.

The ramifications of EJB for distributed object protocols are clear. That is, developers will not be forced to choose IIOP, RMI or DCOM. Instead, they will select the EJB Server that provides the services and tools they need. In effect, EJB adds protocol independence to the Run Anywhere mantra.

The run-time information of the Bean is specified in a deployment descriptor field in an ejb-jar file. The ejb-jar is installed in the EJB Server. It then deploys the bean according to the descriptor fields, such as transaction characteristics. This is a natural extension of the packaging of the Java Beans specification.

Sample Enterprise Bean

This is a good point in the article to provide a sample Enterprise Bean. We will create an account bean, loosely based upon the sample provided in the EJB 0.9 specification. The Bean provider works with an EJB Server provided by ACME corp.

The EJB server provides the ACMEHome, ACMERemote, and ACMEBean classes. The EJB specification provides interface specifications for Home, EJBObject, and EnterpriseBean with it's subtypes - SessionBean and EntityBean. The Bean provider must extend or implement the EJB provided specifications, producing AccountHome and Account interfaces, and the AccountBean class. The tool will then combine the ACME provided classes and interfaces with the bean providers interfaces and class to produce the ACMEAccount, ACMEAccountHome, and ACMEAccountBean classes.

Sample AccountHome.java

public interface AccountHome extends javax.ejb.EJBHome

{

public Account create( String name, double startBalance) throws java.rmi.RemoteException, javax.ejb.CreateException;

}

Sample Account.java

public interface Account extends javax.ejb.EJBObject

{

public void deposit( double depositAmount ) throws java.rmi.Exception;

}

Sample AccountBean.java

import javax.ejb.*;

public class AccountBean implements SessionBean {

// Properties

public String accountName;

public double balance;

protected SessionContext sessionContext;

// Standard Methods

public void deposit( double amount) { balance += amount; }

public void ejbCreate( String accountName, double balance )
throws CreateException, java.rmi.RemoteException {}

// EJB specific methods, often the ejb* are left blank

public void setSessionContext (SessionContext sc) {}

public void ejbRemove () {}

public void ejbActivate () {}

public void ejbPassivate () {}

}

Notice the elegance of the creation of an Account Enterprise Java Bean. Without EJB, we probably would have created an AccountInt interface and an AccountImpl class. EJB simply enforces the separation of the business logic interface from the life-cycle interface, hardly an onerous task.

Sample EJB Client

We will create a client code fragment that creates an Account object, performs a deposit operation, finds a second account, then stores the handle of the object. Note that the sample we created earlier was a session bean, and only entity beans support findBy methods. This sample violates the previous code to show some additional operations that clients can perform on entity beans.

EJBClient.java snippet:

import javax.naming.*;

public class AccountTest

{
public static void main(String[] args) throws Exception
{

Context initialContext = new InitialContext();

AccountHome myAccountHome = (AccountHome)initalContext.lookup

("application/Bank/Account");

Account myAccount = AccountHome.create

("Dave Orchard first Account", 500000);

myAccount.deposit(200000);

// Use entity beans findby method

Account secondAccount = AccountHome.findByLongWindedName

("Dave Orchard second Account");

// Store the object handle

ObjectOutputStream os = ...;

Handle myHandle = secondAccount.getHandle();

os.writeObject( myHandle );

}

}

Potential Problems

EJB has a great deal of promise as well as support from industry and developers. But the EJB spec is only at version 1.0, and suffers from typical first release problems.

These problems should not derail the usage and deployment of EJB, but they are some of the issues that developers will have to face

The EJB specification is very focused on the traditional distributed object protocols. It does not say anything about the distributed environment that did $37 Billion in business in 1997, namely the World-Wide Web. EJB can be useful within the context of web servers, but there are no announced plans to integrate EJB Servers with Web Servers. For now, Java servlets can be used to map HTTP requests to requests on EJB objects. The downside is that the Servlet must use RMI to communicate with the EJB Server. It is possible to run the JavaSoft Java WebServer inside the EJB Server's Java Virtual Machine. A very important next step is to provide tighter integration between a Web Server's Java VM and the EJB Java VM. A prognostication I'll offer is: there will be a 100% Pure Java implementation of an EJB Server accepting local method calls to containers very shortly. This would integrate very well with a Web Server and would provide a natural path for web developers to use.

EJB Deployment

A plethora of vendors have promised to deploy EJB server products. Some of the notables are:

and many more. The reader should take away the knowledge that EJB is being supported by every server company that supports 100% Pure Java.

Conclusion

The Enterprise Java Beans specification provides a great first step in defining how Java developers can build and re-use server logic. There is much more to EJB than this article could hope to cover, so the article has focused on providing some context to fit around the specification.

EJB is a natural extension of "Write Once, Run Anywhere" to middleware and protocols by providing a robust and well-defined framework for developers and vendors. Developers will be able to focus more on business logic, and less on plumbing, while gaining independence from middleware.

All opinions in this article are of the opinion of David Orchard and do not represent any of his past or future employers.