Download - EJB
What is meant by Enterprise Java Beans (EJB) ?
Enterprise JavaBeans (EJB) is a server side component architecture
that enables and simplifies the process of building enterprise class
distributed object applications in Java
Software Components
• A software component is the code that implements a set of well
defined task
• Software Components can be used as puzzle pieces to solve large
problems
• A company can purchase a well defined module that solves a
problem and combine it with other components to solve larger
problems
• For example consider a software component that computes the price
of computer parts such as RAM and hard drives
Software Components (contd.)
• The pricing component calculates the correct price based on a set of
pricing rules
• Base Price – of a single RAM or a single hard disk
• Quantity discounts – that a customer receives for ordering more than
10 RAM modules
• Bundling discounts – that the customer receives for ordering both
RAM and a hard disk
• Preferred customer discounts – that is given to big name customers
• Locale discounts – depending on where the customer lives
Software Components (contd.)
• Overhead costs – such as shipping and taxes
• The pricing rules are not unique for ordering computer parts only
other industries can also use the same pricing functionality
• It will be a huge waste of resources if each company that need
complex pricing calculation to write its own sophisticated pricing
engine
• Vendors provide pricing components that can be reused over and
over again for different customers
• A developer can quickly assemble an application from prewritten
components rather than writing the entire application from scratch
Component Architectures
• There are a number of tools that are available for developing
components like IBM’s VisualAge for Java, Symantec’s Visual Café
and Borland’s JBuilder
• The containers provide a runtime environment for the components to
play in and also provides a set of common services that
components will need
• The component vendors supply’s a set of tools to aid in the
deployment and maintenance of the components like
customization for a particular environment
JavaBeans and EJBs
• JavaBeans are development components and are not deployable
• JavaBeans is not deployable because JavaBeans is not a complete
application
• JavaBeans do not need a runtime environment in which to live
• JavaBeans can have a container or not
• EJBs are deployable components
• EJBs are complete applications
• EJBs need a runtime environment to live
• EJBs need a container
Applets, Servlets and EJBs
• Applets can be deployed in a Webpage and the browser’s applet
viewer provides a runtime container for the applet
• Servlets can be deployed in a Web Server and the web server’s
servlet engine provides a runtime container for the servlet
• Enterprise Java Beans can be deployed in a Application Server and
the application server provides a runtime container for the
Enterprise Java Beans
• The difference between applets, servlets and enterprise java beans is
the domain of which each component type is intended to be a part
Applets, Servlets and EJBs (contd.)
• Applets are portable java programs that can be downloaded and can
execute in an untrusting environment so that an applet can be
downloaded from a Web server into a Web browser deployed in a
Webpage and the browser’s applet
• Servlets are request/response oriented so that they take requests
from client such as Web browser and issue a response back to
that host
• Applets and Servlets are well suited to handle client side operations
performing presentation related logic and lightweight business
logic operations
Applets, Servlets and EJBs (contd.)
• Enterprise Java Beans are server side components that are meant to
perform server side operations such as executing complex
algorithms or performing high volume business transactions
• Server side components needs to run in a highly available, fault
tolerant, transactional and multiuser secure environment
• An application server provides highend server side environment for
the enterprise java beans and provides the runtime containment
necessary to manage enterprise java beans
Multi-tier Architecture
• Any well written software deployment has a logical partitioning into
layers
• Each layer has a different responsibility in the overall deployment
• Within each layer there can be one or more components
• Each layer has a different responsibility in the overall deployment
• A layered system is a well designed system because each layer is
responsible for a separate task
Presentation layer
Business logic layer
Data layer
Multi-tier Architecture (contd.)
• The presentation layer contains components dealing with user
interfaces and user interaction
• The presentation layer of a web based deployment could use java
servlets, Java server pages and Java applets
• The presentation layer contains components that work together to
solve business problems
• The components are written in a high level language like Java
• The data layer is used by the business logic layer to persist state
permanently
Multi-tier Architecture (contd.)
• Central to the data layer is one or more database that house the
stored data
• The advantage of partitioning an application into logical layers is to
isolate each layer from the other so that it will be possible to plug
in a different view
• By introducing the layer partitioning it will be possible to plug in a
different set of business rules or to plug in a different database in
the data layer with relatively minor effects on other layers
Multi-tier Architecture (contd.)
• The physical separation of the layers can be changed according to
the needs
• There is two tier architecture, three tier architecture and even n tier
architecture according to the use
• In a two tier architecture either the business logic is combined with
the presentation layer or the business logic is pushed into the
data layer
• There are many advantages in pushing business logic into the data
layer like saves many round trips, increases the speed of database
operations, reduces total network traffic etc.
Multi-tier Architecture (contd.)
• As the multi tier server side deployments surfaced multitudes of
application servers have begun to appear on the market
• The application servers provide a usable runtime environment in
which components can execute and provide the needed services
• As a number of server side components appeared in the market the
need for a standard architecture for server side components has
arisen
• The standard architecture needs to craft a well formed interface
between the application server which contains the components
and the component themselves
Server Side Component Architecture Solutions
• The most popular standards are
Sun Microsystem’s Java 2 Platform Enterprise Edition (J2EE)
Microsoft’s Distributed InterNet Application Architecture and The
Object Management Group’s CORBA Standard
•The OMG’s Common Object Request Broker Architecture (CORBA) is
a specification and not a product
•The distinction between CORBA and J2EE is that CORBA has only
the
notion of an object and has no notion of deployable server side
component that is automatically managed by an application server
Server Side Component Architecture Solutions (contd.)
• EJB is an integral part of Java 2 Platform Enterprise Edition
• Sun Microsystems first focused on building a robust Java
Development Kit (JDK) which became the de facto reference
implementation of the Java platform
• Sun Microsystems then recognized the power of Java on the server
and began to develop several Enterprise APIs that provided
enterprise level services for server side deployments
• These services served as great feedback to sun because they
highlighted many problems with the Enterprise APIs and that lead
to the development of Enterprise Java Beans
Java 2 Platform Enterprise Edition (J2EE)
• J2EE takes Java’s Enterprise APIs and bundles them together in a
complete development platform for enterprise class server side
deployments in Java
• J2EE addresses all the problems raised by Sun’s Enterprise APIs like
poor synchrony between Enterprise APIs , no way to test
application server compatibility, no reference implementations
• J2EE provides a test suite for vendors to test their products and if
the
product passes the test the product will be called J2EE compliant
• The technologies included with J2EE is shown in the following figure
Java 2 Platform Enterprise Edition (contd.)
Java Data Base Connectivity
Java Remote Method
Invocation
Java Naming and Directory Interface
Enterprise Java Beans
Java Mail
Java IDL Connectors
Java MessagingS
ervice
Java 2 Enterprise
Edition
EXtended Markup
Language
Servlet
Java Server Pages
Java Transaction
API and Java
TransactionService
The Java 2 Platform Enterprise Edition (contd.)
• RMI is a mechanism for invoking methods remotely on other machine
• JRMI is seamless so that a user will not know that he is using RMI
when programming a distributed application
• JRMI abstracts networking issues from the user such as marshalling
parameters, handling machine byte order which are all necessary
for network communications
• JRMI also contains other functions like automatic activation of
remote objects and a distributed garbage collector to clean up
unused remote objects
Java Remote Method Invocation (JRMI)
• EJB relies on JNDI for looking up distributed components across the
network
• JNDI controls the directory service that stores information about
where resources reside and other information such as user name
and passwords
• In EJB when client code requests access to a component, directory
services are used to locate and retrieve a component to service
that client
• There are many types of directory services and is a big problem in
switching to different directory services and JNDI solves the
problem
Java Naming and Directory Interface (JNDI)
• JDBC is a standard Java extension for data accessRMI is a
mechanism for invoking methods remotely on other machine
• Using JDBC programmers can represent database connections,
issue SQL statements, process database results in a relatively
portable way
• JDBC is similar to Open Database Connectivity standard and the two
are interoperable through JDBC-ODBC bridge
• JDBC contains built in support for database connection pooling
Java Database Connectivity (JDBC)
• A transaction is a unit of work that makes a set of guarantee about its
execution
• Any code executing within the scope of a transaction is guaranteed
either to all be executed or not to execute at all
• Transactions allow for multiple users to be modifying the same data
yet each to be isolated from one another
• JTA is a high level transaction interface that is used to control
transactions
Java Transaction API (JTA) and Java Transaction Service (JTS)
• JTS is a set of low level transaction interfaces that is used behind
the scenes and the client code do not directly interact with JTS
• JTS makes it possible for multiple vendors to collaborate when
performing in a distributed heterogeneous environment
• Enterprise Java Beans strictly depends on JTA but it does not
depend on JTS
Java Transaction API and Java Transaction Service (contd.)
• A messaging service allows for distributed objects to communicate
in an asynchronous reliable manner
• Processes can respond to messages at their leisure and they could
potentially be offline when a message is initially sent
• Java Messaging Service can be used as a portable messaging
service
Java Messaging Service (JMS)
• Servlets are networked components that can be used to extend the
functionality of a Web server
• Servlets are request response oriented in that they take from client
host and issue a response back to that host
• Servlets differ from EJB components is that the server side
component features that EJB offers is not readily available to
servlets
• Servlets are suitable to handle simple request response needs and
they do not require sophisticated management by an application
server
Java Servlets
• Java Server Pages are very similar to servlets and JSP scripts are
compiled into servlets
• JSP scripts are not pure Java code but more centered around look
and feel issues
• JSP can be easily written and maintained by non Java programmers
• JSP do not require a Java compiler
Java Server Pages (JSP)
• Java IDL is an implementation of the CORBA specification in Java
and it allows for connectivity and interoperability with
heterogeneous objects
• CORBA is a cross platform architecture
• CORBA is language independent and it does not matter what the
programming language is as long as CORBA supports the
language in which the program is developed
• Java IDL is one specific implementation of CORBA among many
such
implementations
Java IDL
• JavaMail API allows applications to use E-mail capabilities
• JavaMail defines a set of interfaces to which the application code is
written and those interfaces shield the code from specific
protocols or mail service implementations used
• The Internet mail code becomes portable across platforms as well as
across mail protocols
• JavaMail depends on the JavaBeans Activation Framework (JAF) to
encapsulate message data and to handle interactions with that
data
JavaMail
• A connector is a vendor specific bridge that links an existing system
to the Java 2 Platform Enterprise Edition
• The existing system could be ERP systems, mainframe systems such
as IBM’s CICS or existing legacy databases
• Connectors are useful because they will take care of navigations to
existing systems, handling transaction and security concerns
• The connectors are different from the other J2EE APIs because
connectors are very vendor specific
Connectors
• EJB partitions the responsibility of an EJB development to six
different parties and they are
• The Bean Provider
• The Container Provider
• The Server Provider
• The application assembler
• The deployer
• The System Administrator
The Six Parties
• The Bean Provider is the party who supplies enterprise beans
components having methods for performing application logic
• The Bean Provider is a vendor of components
• The Bean should be designed correctly to be reusable considering
the different applications, domains and users of the Bean
• Developing a reusable bean will require many iterations depending
on the feedback from the customers using the Bean
• Bean reusability fall into three different levels
The Bean Provider
• Reuse as given
• The application assembler uses the bean as it is to build an
application
• The Bean functionality cannot be tailored to fit the application
• Reuse by customization
• The application assembler configures the bean by modifying the
bean properties to fit the specific needs of the application
• Reuse by extension (subclass)
• The application assembler creates custom application specific bean
by subclassing the prebuilt acquired beans
The Bean Provider (contd.)
• Reuse by extension is more powerful but difficult to achieve and is
only provided by very few providers
• The more reusability a bean provides the more useful a bean is
• Enterprise beans can range in size and scope like smaller grained
enterprise beans which are very concrete with limited scope and
duties and larger grained enterprise beans
•A bean can be a client of another bean eg. Credit card transaction
The Bean Provider (contd.)
Server Bean for processing transactions
Client Bean for credit card scanner
Verifier Bean
• The EJB container provides a playground for the enterprise java
Beans to run
• There can be many Beans running with in a container
• Bean containers are responsible for managing the beans running
within them
• The Container interact with the beans by calling a few required
methods that the bean must expose
• The Containers can also provide access to legacy systems
The Container Provider
• An application server provides services for the application such as
transaction services, security services etc.
• The services are needed for the application to be scalable, robust
and
secure for multiple concurrent users
• The EJB server provides a runtime environment for one or more
containers
• EJB servers manage low level system resources allocating resources
to containers as they are needed
The Server Provider
Enterprise Java Bean1
Enterprise Java Bean2
Enterprise Java Bean3
Enterprise Java Bean4
EJB Container 1 EJB Container 2
EJB Server
The relationship between EJB servers and EJB containers
• The Servers and containers provide both implicit services and
explicit services
• The implicit services include
• Implicit distributed transaction management
• Implicit security
• Implicit resource management and component life cycle
• Implicit persistence
• Implicit remote accessibility
• Implicit multiclient support
• Implicit component location transparency
EJB Server and container responsibilities
• The explicit services include
• Naming and directory service – allowing components to be located
across the network
• A set of deployment tools – that allows the EJB deployer to deploy
components into the EJB server and customize the components
as needed
• Intelligent load balancing
• Server clustering
• Connectors to legacy systems like SAP
EJB Server and container responsibilities (contd.)
• The application assembler assembles the reusable deployable
server side components to solve a business problem
• The application assembler can be a staff or an outside consultant
who understands the complete application system and know how
the various components fit together
• The tasks that an application assembler should perform are
1. Write the code that calls on components purchased from vendors
2. Provide a workflow solution between a number of disparate
components mapping between them
The Application Assembler
3. Supply an user interface if needed ( using JSP or servlets )
4. Write new enterprise beans to solve domain specific problems eg.
Business entity that is specific for a particular business
• The application assembler should be involved in the design and
implementation of logic residing in several tiers in a multi tier
architecture
The Application Assembler (contd.)
• The application assembler may not be familiar with the specific
operational environment that the application must run in
• The EJB deployers are aware of specific operational environment
and
know how to deploy beans within servers and how to customize
the beans for a specific environment
• The EJB deployer has knowledge of a customer’s existing naming
and directory services and understands how to customize
enterprise Beans for that scenario
• Another function of EJB deployer is mapping security settings
The EJB Deployer
• The Business stores the list of their employees and their security
levels in some directory service structure and the EJB deployer
must adapt the access level of the beans to fit the particular
environment
• The EJB deployers must be aware of the differences between the
various beans, servers and containers available in the market
• The EJB deployer can be also a staff or an outside consultant
The EJB Deployer (contd.)
• The system administrator is responsible for the upkeep and
monitoring of the deployed system and make use of runtime
monitoring and management tools that the EJB server and
containers provide
• Good EJB deployments might page the system administrator if a
serious error occurs that require immediate attention
• Some EJB Products have hooks into professional monitoring
products for helping system administrator
The System Administrator
• An Enterprise Java Beans is a server side software component that
can be deployed in a distributed multi tier environment
• The client of a enterprise java beans can be a servlet, an applet or
even another enterprise java bean
• The client request to a bean can result in a whole chain of beans
being called resulting in subdividing a complex task into subtasks
handled by simple beans
• There are two different kinds of enterprise java beans the session
beans and the entity beans
Enterprise Java Beans
• Session beans are business process objects that implements
business logic, business rules and workflow
• Session beans are reusable components that contain logic for
business processes
• A session bean can perform price quoting, order entry, video
compression, banking transactions, stock trades, complex
calculations etc.
Session Beans
• Session beans are called session beans because they live for about
as long as the session of the client code that is calling the
session bean exists
• Session beans are usable by one client at a time and they are not
shared between clients
• The EJB container is responsible for managing the lifetime of beans
• The container destroys session beans at the appropriate time
• There are two subtypes of session beans the stateful session beans
and stateless session bean
Session Beans (contd.)
• Some business processes can be performed in a single method
request other business processes can last across multiple
method requests and transactions
• A stateful session bean is a bean that is designed to service
business
processes that span multiple method requests or transactions
• The stateful session beans retain state on behalf of an individual
client so in a stateful session bean’s state is changed during a
method invocation the same state will be available for the client in
the following invocation
Stateful Session Beans
• A stateless session bean is a bean that is designed to service
business processes that have a single request
• A single request business process does not require state to be
maintained across method invocations
• An example for stateless session bean is video compression where
the client could pass in a buffer of uncompressed data as well as
a compression factor and the bean would return a compressed
buffer and the bean does not retain any state
• Another example is a credit card verification component
Stateless Session Beans
• An Entity bean is a component that represents persistent data
• Entity beans represent real data objects such as customers,
products
employees, bank accounts, orders, stock portfolios etc.
• Entity bean do not contain business process logic rather they model
data
• Session beans use entity beans to represent the data session bean
uses
• The Entity bean is an object oriented in memory view of a database
Entity Beans
• It is possible to read an entire set of data out of a database at once
into an in memory entity bean component and then manipulate
this entity bean by calling methods on it
• An entity bean implements the data access logic layer in a multi tier
architecture
Entity Beans (contd.)
Entity Bean
Client code such as applet
EJB Container Permanent Storage
• Entity bean survive critical failures such as application server
crashing because entity beans are representation of data in a
permanent database
• Entity beans have a life cycle much longer than Session beans even
years depending on how long data sits in the database
• Multiple clients can use Entity beans simultaneously
• One client can isolate from another by using transactions
• Transactions guarantee multiple clients to perform persistent
operations independently of one another
Entity Beans (contd.)
• Entity beans can be used with legacy database where data is already
inside
• The data that entity beans model could exist in a database before a
company decided to employ Enterprise Java Beans
• Database records can be read in and interpreted as objects in almost
any language and EJB takes advantage of this and allows for the
transformation of a database’s data into Java object
• There are two subtypes of entity beans the bean managed
persistent
entity beans and container managed persistent entity beans
Entity Beans (contd.)
• Entity beans are persistent components because their state is saved
to a secondary storage such as a relational database
• A bean managed persistent entity bean is an entity bean that must be
persisted by the component developer
• The component developer must write code to translate the in memory
fields into an underlying data store such as a relational database
• The component developer must handle the persistent operations
including saving, loading and finding data within the entity bean
Bean Managed Persistent Entity Beans
• In Container managed persistent entity bean the container provides
an automatic persistence for the entity beans
• The container performs every function including saving loading and
finding component data
• The developer just describe what should be persisted to the
container and it will persist for the developer
• The container gives theoretical database independence allowing the
developer to switch one data store for another
• The EJB containers perform a wide variety of mapping functionality
Container Managed Persistent Entity Beans
• Why EJB offers various kinds of beans
• Sun is not the only company involved in constructing the Enterprise
Java Beans standard
• Many companies have been involved each with customers that have
different kinds of distributed systems and to accommodate the
needs of different enterprise applications sun decided for
different kinds of beans
• By offering various kinds of beans EJB provides increased
functionality
Motivation for Multiple Bean Types
• How to decide what to put in a session bean and what to put in an
entity bean
• The key difference between the two are that session bean represent
business processes and business logic and entity bean holds
permanent business entities such as businesses data and data
related logic
• Consider an example where a customer wants to order 15
workstations
Session Beans versus Entity Beans
• The pricer component is represented by a session bean, after the
price is calculated the pricer is free to service another client
• When the customer places the order an order entity bean is used to
put up the order
• The order is fulfilled by another session bean that contains the logic
to do so
• Session beans model a current business process which can be tuned
with different algorithms and approaches
Session Beans versus Entity Beans (contd.)
• Entity bean defines the core business data such as purchase orders,
customers and bank accounts that do not change very much
over time
• In practice entity beans achieve a higher level of reuse
• Session beans never embody permanent data but merely provide
access to data
• Session beans are not persistable they represent business processe
• Entity beans embody data and are persistable
Session Beans versus Entity Beans (contd.)
• The most important responsibility of an EJB container is to provide
an environment in which enterprise beans can run
• EJB containers house the enterprise beans and make them available
for clients to invoke remotely
• The container is responsible for connecting clients to beans,
performing transaction coordination, providing persistence,
managing a beans life cycle etc.
• EJB containers are a huge challenge to write because they are so
complex and perform so many tasks
EJB Container Responsibilities
• The features an EJB container provides are
• Resource Management and Bean Life Cycle Management
• State Management
• Transactions
• Security
• Persistence
• Remote Accessibility and Location Transparency
• Glue Code and Bean Installation Tools
• Specialized Container Features
EJB Container Responsibilities (contd.)
• The container is responsible for providing all resource management
services
• The resources include threads, socket connections, database
connections and more
• The EJB container is also responsible for controlling the life cycle of
the deployed enterprise bean components
• As client request arrive the EJB container dynamically instantiates,
destroys and reuses beans as appropriate
Resource Management and Bean Life Cycle Management
• If a client request a certain type of bean that does not exist in
memory the EJB container may instantiate a new in-memory
instance in behalf of the client
• If a new bean has to be instantiated and the system is low in memory
then the container can destroy some beans that are not being
used anymore and this is called instance pooling
• The EJB container is responsible for coordinating the entire effort of
resource management as well as managing the deployed bean’s
life cycle
Resource Management and Bean Life Cycle Management (contd.)
• A bean can be a stateless bean or a stateful bean
• A stateless bean can be reassigned to other clients dynamically by
the EJB container because there is no state lost from the primary
client
• The reuse of beans results in incredible resource gains
• If a client times out the EJB container destroys the bean or reuse it
• In a stateful bean the EJB container should do the state management
to service multiple clients
State Management
• Entity beans are inherently stateful because they represent data
• Consider the case when a new client request a component and the
container has reached the limit
• The container can take a component that hasn’t been used for a
while
and write the state out to disk and the bean can be reassigned to
a different client
• When the original client makes a request the original client’s bean
state can be read back in from disk in a different in-memory bean
object and use it again
State Management (contd.)
• A transaction is a series of operations that appear to execute as one
large atomic operation
• Transactions allow multiple users to share the same data and they
guarantee that any set of data they update will be completely and
wholly written
• Transactions ensure that database data is kept consistent
• The EJB container handles the underlying transaction operations
coordinating efforts behind the scenes between transaction
participants
Transactions
• The role of EJB container in security is to handle the validation of
users for tasks they wish to accomplish
• An Access Control Lists (ACL) is a list of users and their rights is
used to validate
• If the user has the correct rights he can perform the desired
operation
Security
• Entity beans are persistent objects that represent data in an
underlying storage
• EJB containers provide the transparent persistence of container
managed persistent entity beans
• From EJB 1.1 specification onwards the container managed
persistence came to reality
Persistence
• The EJB container insulates the bean from all networking issues
• Enterprise Java Beans are written as standalone nonnetworked
components but once deployed in the container they become
distributed components deployable across multiple tiers
• EJB containers use Java Remote Method Invocation interfaces to
specify remote accessibility
•The benefit of distributed communication technologies like JRMI is
that the client code will be unaware of the physical location of
the component it is calling
Remote Accessibility and Location Transparency
• The client should be totally unaware of where the component really is
whether the component is local or remote should be transparent
to the client and this is known as location transparency
• In the bean the machine location should not be hard coded because
it
is an essential part of reusable component that can be deployed
in a wide variety of multitier situations
• If a machine that has components crashes it will be possible to
reroute client invocations to other machines without the client
even knowing about the crash
Remote Accessibility and Location Transparency (contd.)
• Each EJB container ships with a suite of glue-code tools which are
meant to integrate beans into the EJB containers environment
• The container’s glue code tools are responsible for transforming an
enterprise bean into fully managed distributed server side
component • The glue code involves logic to handle resource management, life cycle, state management , transactions, security, persistence and
remote accessibility
Glue Code and Bean Installation Tools
• Other than the normal duties of a container specialized containers
can provide additional qualities of services
• If a bean depends on particular qualities of service it may not run in
other containers
• Some containers may provide a way to perform customized load
balancing between distributed components
• A high end EJB container may also provide dynamic resizing of
managed resources and components
Specialized Container Features
• eg. If clients are less active at night than during the day then a
smaller pool of resources is only required at night
• Some other specialized container functions are
• Integration to mainframe systems
• Distributed transactions
• Complex database persistence services
• Integrated XML facilities
• CORBA integration and support
Specialized Container Features (contd.)
Introduction to Session Bean
• In order for a bean to work in any container and to work with any
client of that bean the bean must adhere to a well defined interface
• The EJB provides the enterprise bean component implementation in
an enterprise bean class
• An enterprise bean class contains implementation details of the
component
• The session beans of enterprise bean class contain business
process related logic such as logic to compute prices, transfer
funds between bank accounts or perform order entry
The Enterprise Bean Class
• The EJB specification defines a few standard interfaces that the bean
class should implement
• These interfaces force a bean to expose certain methods that all
beans must provide as defined by the EJB component model
• The container calls these required methods to manage a bean and
alert the bean to significant events
• The basic interface that all bean classes must implement is the
javax.ejb.EnterpriseBean interface
The Enterprise Bean Class (contd.)
public interface javax.ejb.EnterpriseBean extends java.io.Serializable
{ }
•Both session beans and entity beans have more specific interfaces
• All session beans must implement javax.ejb.SessionBean while all
entity beans must implement javax.ejb.EntityBean
• The Enterprise java bean class never needs to implement the
javax.ejb.EnterpriseBean interface directly rather the bean class
implements the interface corresponding to its bean type
The Enterprise Bean Class (contd.)
• A client wants to use an instance of an enterprise bean class the
client never invokes the method directly rather the invocation is
intercepted by the EJB container and then delegated to the bean
• The enterprise bean class can not be called across the network
directly because an enterprise java bean class is not network
enabled
• It is the EJB container that handles networking by wrapping the bean
in a network enabled object
The EJB Object
• The network enabled object receives calls from client and delegates
these calls to instances of the bean class
• The EJB container can automatically perform some management
issues like transaction logic, security logic, bean instance
pooling logic etc
• The EJB container is acting as a layer of indirection between the
client and the bean and the layer of indirection manifests itself
as
a single network aware object called the EJB object
The EJB Object (contd.)
The EJB Object (contd.)
Enterprise
Java Bean
EJB Object
Client Code
Call a m
ethod
Acquire a Bean and
delegate the method to
the Bean
EJB Container
Remote Interface
Home
Object
Home Interface
• The EJB Object is an intelligent object that knows how to perform
intermediate logic that the EJB container requires before a
method call is serviced by a bean class instance
• The EJB object acts as glue between the client and the bean and it
exposes every business method that the bean exposes
• EJB objects delegate all client requests to beans
• All EJB objects have container specific code inside them
The EJB Object (contd.)
• EJB object can be thought as a physical part of the EJB Container
• Each bean’s EJB object is different so that the container vendor
supplies glue code tools that generate the class file for the EJB
object automatically
The EJB Object (contd.)
• The clients invoke methods on EJB objects rather than the beans
themselves so the EJB objects must clone every business
method that the bean exposes
• An interface is created which duplicates all the business logic
methods that the corresponding bean exposes and this interface
is called the remote interface
• Remote interfaces must comply with the rules that the EJB
specification defines like all remote interfaces must derive from
a
common interface called javax.ejb.EJBObject
The Remote Interface
public interface java.ejb.EJBObject extends java.rmi.Remote
{ public abstract javax.ejb.EJBHome getEJBHome()
throws java.rmi.RemoteException;
public abstract java.lang.Object getPrimaryKey()
throws java.rmi.RemoteException;
public abstract void remove()
throws java.rmi.RemoteException, javax.ejb.RemoteException;
public abstract javax.ejb.Handle getHandle()
throws java.rmi.RemoteException;
The Remote Interface (contd.)
public abstract boolean isIdentical(javax.ejb.EJBObject)
throws java.rmi.RemoteException; }
• These methods are the required methods that all EJB objects must
implement
• The client code that wants to work with the beans calls the methods
in javax.ejb.EJBObject
• When a bean’s client invokes any of the business methods the EJB
object will delegate the method to its corresponding
implementation which resides in the bean itself
The Remote Interface (contd.)
METHOD EXPLANATION
getEJBHome() Retrieves a reference to the corresponding home object
getPrimaryKey() Returns the primary key for the EJB object and is only used by entity beans
remove() Destroys the EJB object. When the client code is done with using an EJB object this method is called . The system resources for the EJB object can be reclaimed . With entity beans remove() also deletes the bean from the underlying persistent store
getHandle() Acquires a handle for the EJB object. An EJB handle is a persistent reference to an EJB object that the client can stow away somewhere. Later on the client can use the handle to reaquire the EJB object and start using it again
IsIdentical() Tests whether two EJB objects are identical
The Remote Interface (contd.)
• The javax.ejb.EJBObject extends java.rmi.Remote interface which is
a
part of Java Remote Method Invocation (JRMI)
• Any object that implements java.rmi.Remote is a remote object and is
callable from a different Java Virtual Machine
• The EJb object provided by the container implements the remote
interface by the help of java.rmi.Remote as a result the EJB
object becomes fully networked object able to be called from
other machines located elsewhere on the network
Java RMI and EJB Objects
• EJB remote interfaces must conform to Java RMI’s remote interface
rules like all methods should throw a remote exception using
java.rmi.RemoteException
• A remote exception indicates that something unexpected happened
on the network like netwok problem or machine failure while
invoking a bean
• Remote interfaces must conform to Java RMI’s parameter passing
conventions
Java RMI and EJB Objects (contd.)
• In JRMI the physical location of the remote object is masked so the
client code is unaware of whether the EJB object it is using is
located on a machine next door or a machine across the internet
• EJB guarantees location transparency of distributed components
this means the client code is portable and not tied to a specific
multitier deployment configuration
• A more portable version of Java RMI called RMI-IIOP is now available
that provides interoperability with CORBA systems
Java RMI and EJB Objects (contd.)
• How do clients acquire references to EJB objects
• The client cannot instantiate an EJB object directly because EJB
objects could exist on a different machine than the client is on
and the client will not be aware of exactly where the EJB object
reside
• To acquire a reference to an EJB object the client code asks for an
EJB object from an EJB object factory which is responsible for
instantiating and destroying EJB objects
• The EJB specification calls such a factory a home object
The Home Object
• The responsibilities of home object are
• Create EJB objects
• Find existing EJB objects
• Remove EJB objects
• Like EJB objects, home objects are proprietary and specific to each
EJB container
• Home objects are physically part of the container and are auto
generated by the container vendor tools
The Home Object (contd.)
• Home interfaces define methods for creating destroying and finding
EJB objects
• The containers home object implements home interface
• EJB defines some required methods that all home interfaces must
support and these required methods are defined in the
javax.ejb.EJBHome interface
• The parent javax.ejb.EJBHome derives from java.rmi.Remote this
means the home interfaces are fully networked Java RMI remote
objects
The Home Interface
• Deployment descriptors enable EJB containers to provide implicit
middleware services to the enterprise java bean components
• An implicit middleware service is a service that the beans gain
without coding to any middleware API, the beans gain the
service automatically
• The middleware service include life cycle management, persistence,
transaction control and security services
• The deployment descriptor specifies the requirements of the bean
and they are
Deployment Descriptors
• Bean management and life cycle requirement : The deployment
descriptor settings indicate how the container should manage
the beans and specify if the bean is a session or entity bean
• Persistence requirement (entity bean only) : Authors of entity beans
use the deployment descriptors to inform the container about
whether the bean handles the persistence on its own or
delegates the persistence to the EJB container
• Transaction requirements : The transaction settings for a bean can
be specified in the deployment descriptors. These settings
Deployment Descriptors (contd.)
control what the bean requirements are for running in a
transaction
• Security requirements : Deployment descriptors contain access
control entries which the beans and container use to control
access control to certain operations
• The deployment descriptor specify who is allowed to use which
beans and even who is allowed to use each method on a
particular bean
Deployment Descriptors (contd.)
• It is the responsibility of a bean provider to create a deployment
descriptor
• When an application assembler is piecing together an application
from beans he can tune the deployment descriptor
• The deployment descriptor declare how the beans should use
middleware rather than writing code that uses middleware
• By having a separate customizable deployment descriptor it is easy
to fine tune components to a specific deployment environment
without changing the source code
Deployment Descriptors (contd.)
• A Java based properties file will be included with the bean
• The bean read these properties at runtime and use the properties to
tune how the bean functions
• eg. A computation bean can use properties to enable selection of an
algorithm to use
• A pricing bean could use properties to customize pricing rules
Bean Specific Properties
• Once the bean classes, home interfaces, remote interfaces,
deployment descriptors and bean properties are ready they can
be packed into an entity called the Ejb jar file
• It is a compressed file that follows the .ZIP compression format
• Once the Ejb jar file is made the enterprise bean is complete and is a
deployable unit within an application server
• To install the EJB objects the jar file is decompressed , extracted and
the EJB objects and home objects are generated and deployed
into an application server
Ejb jar File
• Session beans are intended to represent business processes
• A business process task involves logic, algorithms and workflow
• Some examples of processes that can be represented using session
beans are billing a credit card, fulfilling an order and trading
stock
Session Bean
• A Session beans is a relatively short lived component
• The session bean has a life time equivalent to a client’s session
• The EJB container is empowered to destroy session beans if client
times out
• Session beans do not survive machine crash or application server
crashes
Session Bean Lifetime
•Session beans are nonpersistent as they are not saved to permanent
storage still they can perform database operations
• All session beans must expose required management callback
methods
• The container uses the callback methods to initialize and destroy
a bean and the callback methods are not intended for clients
Session Bean Lifetime (contd.)
• A conversation is an interaction between a client and a bean
• A stateless session bean is a bean that holds conversation that span
a single method call
• A stateless session bean clears itself out all information pertaining to
the past invocation
• Stateless session bean store no conversational state from method to
method
• They are stateless because they do not hold multimethod
conversations
Conversational versus Nonconversational Session Beans
• Any stateless session bean can service any client request because
they are all exactly the same
• Stateful session beans are components that hold conversations with
clients that may span many method calls
• During a conversation the bean holds conversational state for that
client
Conversational versus Nonconversational Session Beans (contd.)
• When a method is called on a session bean instance the EJB
container guarantees that no other clients are using that instance
• If multiple clients simultaneously invoke methods on a session bean
the invocations are serialized or performed in lock step
• The container automatically makes clients line up one by one to use
a
bean instance
• The container can provide other instances of the bean to service
multiple clients simultaneously
All Session Bean Methods are Serialized
• The session enterprise bean class must implement the
javax.ejb.SessionBean interface which extends
javax.ejb.EnterpriseBean
• The interface defines a few required methods that the EJB container
calls on the bean to alert it about important events
• Clients of the bean will never call these methods because these
methods are not made available to clients via EJB object
• Entity beans have their own interface called javax.ejb.EntityBean
which also inherits from javax.ejb.EnterpriseBean
Understanding How to write Session Beans
public interface java.ejb.SessionBean extends
javax.ejb.EnterpriseBean
{ public abstract void setSessionContext(SessionContext ctx)
throws java.rmi.RemoteException;
public abstract void ejbPassivate()
throws java.rmi.RemoteException;
public abstract void ejbActivate()
throws java.rmi.RemoteException;
public abstract void ejbRemove()
throws java.rmi.RemoteException; }
Understanding How to write Session Beans (contd.)
• The container calls setSessionContext() to associate a bean with a
session context
• A session context is a beans gateway to interact with the container
• The bean can use session context to query the container about the
current transactional state, current security state and more
• A typical bean implementation would store the context away in a
member variable so the context can be queried later as shown in
the following example
setSessionContext(SessionContext ctx)
Import javax.ejb.*;
public class MyBean implements SessionBean {
private SessionContext ctx;
public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
}
………..
}
setSessionContext(SessionContext ctx) (contd.)
• The ejbCreate() method initialize the session bean
• Different ejbCreate() methods can be defined with different
arguments
• Clients can initialize the beans in different ways because there are
different ejbCreate(…) method signatures
• At least one ejbCreate() method must be provided in a session bean
• The implementation of ejbCreate(…) should perform initialization of
beans such as setting member variables to the argument values
passed in as shown in the following example
ejbCreate(…)
Import javax.ejb.*;
public class MyBean implements SessionBean {
private int memberVariable;
public void ejbCreate(int initialValue) {
this.memberVariable = initialValue;
}
………..
}
ejbCreate(…) (contd.)
• The ejbCreate() methods are callback methods that the container will
invoke
• Client code never calls ejbCreate() method because clients never
deal
with beans directly they must go through the container
• Clients must have some way to pass parameters to ejbCreate()
method because clients supply the initialization parameters
• A home interface is the factory interface that clients call to initialize
the bean so each ejbCreate() method must be duplicated in the
home interface
ejbCreate(…) (contd.)
• If too many beans are instantiated the EJB container can passivate
some of them by writing the beans to a temporary storage
• The container can then release the resources the beans had claimed
• The beans implementation of the ejbPassivate() should release any
resources the bean may be holding
ejbPassivate( )
Import javax.ejb.*;
public class MyBean implements SessionBean {
public void ejbPassivate() {
<close socket connections, etc….>
}
………..
}
ejbPassivate ( ) (contd.)
• If the client needs to use a bean that has been passivated the
container brings the bean back into memory and activates it
• Immediately after the bean is activated the container calls the
ejbActivate() method
import javax.ejb.*;
public class MyBean implements SessionBean {
public void ejbActivate() {
<open socket connections, etc….>
}
………..
}
ejbActivate( )
• If a container wants to remove the session bean it calls the
ejbRemove() callback method
• ejbRemove() is a clean up method which takes no parameters
• There is only one ejbRemove() method per bean
import javax.ejb.*;
public class MyBean implements SessionBean {
public void ejbActivate() {
<open socket connections, etc….>
}
………..
}
ejbRemove( )
• There are two types of methods the callback methods and the
business methods
• The business methods actually solve business problems
• For clients to call the business methods the business methods must
be listed in the remote interface
import javax.ejb.*;
public class MyBean implements SessionBean {
public int add(int i, int j) {
return (i + j);
}
Business methods
• Calling the session beans takes place in four steps and they are
• Look up a home object
• Use the home object to create an EJB object
• Call business methods on the EJB object
• Remove the EJB object
Understanding How to call Session Beans
• Java Naming and Directory Service (JNDI) provides a standard
interface for locating users, machines, networks, objects and
services
• In J2EE , JNDI is used for locating resources across an enterprise
deployment like home objects, environment properties, database
resources etc.
• There are two common steps that must be taken to find any
resources in a J2EE deployment
Looking Up a Home Object
1. Associate the resource with a nickname in the deployment
descriptor, the J2EE product will bind the nickname to the resource
2. Clients of the resource can use the nickname with JNDI to look up
the resource across a deployment
• EJB containers mask the specific locations of home objects from
the client
• Clients do not hard code the machine names that home objects
reside on but rather they use JNDI to look up home objects
• For clients to locate a home object a nickname must be provided for
the beans home object
Looking Up a Home Object (contd.)
• Clients will use the nickname to identify the home object it wants
• JNDI goes over the network to some directory service to look for the
home object and when the home object is found a reference to it
is returned to the client
• To retrieve the home object a JNDIlookup() operation must be
performed on the remote directory
• The following figure shows how to call a session beans
Looking Up a Home Object (contd.)
Client Home Object
EJB Object
Enterprise Java Beans
JNDI
1 2
3
45
67
EJB Container
1. Retrieve Home Object Reference
2. Return Home Object Reference
3. Request to create a new EJB object
4. Create EJB Object
5. Return EJB object reference
6. Invoke business method
7. Delegate request to Bean
• As the client code has a reference to the home object then a call is
made to the home object which acts as a factory to create EJB
object
• To create an EJB object call one of the create() methods on the home
• In case of stateless session beans no initialization parameters are
required to call the create() method
• When create() method is called the bean’s instance ejbCreate()
method may not be called because the container can pool and
reuse existing beans
Creating an EJB Object
• As the client has an EJB object it can start calling one or more of the
methods that the bean exposes through the EJB object
• When the client calls a method on the EJB object the EJB object
must choose a bean instance to service the request
• The EJB object may need to create a new instance or reuse an
existing instance
• When the bean instance is done the EJB object takes the return value
from the beans method and ships it back to the client
Calling a Method
• When to destroy an EJB object call a remove() method on the EJB
object or home object
• The remove() method enables the container to destroy the EJB object
• As with creating a bean destroying a bean might not necessarily
correspond with literally destroying in memory bean objects
because the EJB container controls their life cycles to allow
for pooling between heterogeneous clients
Destroying the EJB Method
The Basics of Stateless Session Beans
• Stateless session beans are components that model business
processes that can be performed in a single method call
• All stateless beans appear identical to clients so clients cannot tell
them apart
• Stateless session beans cannot retain state between method calls
they also cannot retain state after a client passes data to an
ejbCreate() cal
• Stateless session beans do not take any parameters clients never
supply any critical information that bean instances need to start
Characteristics of Stateless Session Beans
• As stateless session beans do not take parameters so the EJB
containers can precreate instances of stateless session beans
•The EJB containers can pool stateless session bean instances before
the client connects and when a client calls a method the
container can retrieve an instance from the pool have it serviced
and then return it to the pool
• The container dynamically assign instances of the bean to different
clients
Characteristics of Stateless Session Beans (contd.)
• The benefit of bean instance pooling is that the pool of beans can be
much smaller than the actual number of clients connecting
• Bean pools do not need to be statically sized they can be dynamically
resized according to the demand
• If more clients connect to the deployment during day than night then
the container might allow to have a large pool during day and a
small pool at night which frees system resources for other tasks
during off-peak hours
Characteristics of Stateless Session Beans (contd.)
• Because the beans are pooled and reused they are decoupled from
EJB objects
• The bean can be reassigned at any time to another EJB object
depending on the containers strategy
• A new bean does not necessarily have to be created at the same time
an EJB object is created rather a bean can be taken from the
available pool
• If client load suddenly increases more beans can be instantiated by
the EJB container at any time
EJB Object Decoupling
• In this stateless session bean a component running in a distributed
object framework will be responsible for returning the string
“Hello World” to the client
• The first step is coding the bean’s remote interface
• The remote interface duplicates every business method that the
beans expose
• The EJB object will delegate all client requests to actual beans
• The following program is the remote interface of Hello World
Writing a Hello World Stateless Session Bean
package com.session.helloworld;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.rmi.Remote;
/* This is the HelloBean remote interface.
This interface is what clients operate on when they interact with
EJB objects. The container vendor will implement this interface,
the implemented object is the EJB object, which delegates
invocations to the actual bean.
*/
Hello World remote interface source code
public interface Hello extends EJBObject {
/*
The one method - hello - returns a greeting to the client.
*/
public String hello() throws RemoteException;
}
Hello World remote interface source code (contd.)
Hello World remote interface explanation
• The javx.ejb.EJBObject is extended so that the container generated
EJB object which implements the remote interface will contain
every method that the javax.ejb.EJBObject interface defines
• There is a business method hello() which returns the string “ Hello
World “ back to the client
• As the remote interface is a Java RMI remote interface that extends
java.rmi.Remote , it must throw a remote exception and that is
the only difference between the remot interfaces hello()
signature and the beans hello() signature
• The exception indicates a networking or other critical problem
package com.session.helloworld;
import javax.ejb.*;
/*
Demonstration stateless session bean.
*/
public class HelloBean implements SessionBean {
/* EJB-required methods */
public void ejbCreate() {
System.out.println("ejbCreate()");
}
public void ejbRemove() {
System.out.println("ejbRemove()");
}
Hello World bean source code
public void ejbActivate() {
System.out.println("ejbActivate()");
}
public void ejbPassivate() {
System.out.println("ejbPassivate()");
}
public void setSessionContext(SessionContext ctx) {
System.out.println("setSessionContext()");
}
// Business methods
public String hello() {
System.out.println("hello()");
return "Hello, World!";
} }
Hello World bean source code (contd.)
Hello World bean explanation
• The required container callback methods are also added to the code
• The bean implements javx.ejb.SessionBean interface which makes
the bean a session bean
• The bean is stateless and has an identical initialization method a
simple ejbCreate() that takes no parameters
• When the bean is destroyed there is nothing to clean up so a very
simple ejbRemove() method can be used
Hello World bean explanation
• The setSessionContext() method associates a bean with an
environment
• The ejbActivate() and ejbPassivate() methods are used when beans
are activated and passivated and they do not apply to stateless
session beans so the methods are empty
Hello World home interface source code
package com.session.helloworld;
import javax.ejb.*;
import java.rmi.RemoteException;
/*
This is the home interface for HelloBean. This interface is
implemented by the EJB Server's glue-code tools – the
implemented object is called the Home Object, and serves as a
factory for EJB Objects. One create() method is in this Home
Interface, which corresponds to the ejbCreate() method in
HelloBean.
*/
Hello World home interface source code (contd.)
public interface HelloHome extends EJBHome {
/*
This method creates the EJB Object
@return The newly created EJB Object.
*/
Hello create() throws RemoteException, CreateException;
}
Hello World home interface explanation
• Home interface specifies mechanisms to create and destroy EJB
objects
• The home interface extends javax.ejb.EJBHome which is required for
all home interfaces
• EJBHome defines a way to destroy an EJB object so there is no
need
to write a method to destroy an EJB object
• The home interface exposes one method to create an EJB object and
takes no arguments because this is a stateless session beans
• The create method throws a java.rmi.RemoteException because
home object is a networked RMI remote object
Writing the Deployment Descriptor
• The deployment descriptor describes a bean’s middleware
requirements to the container
• Deployment descriptors are one of the key features of EJB because
they allow to declaratively specify attributes on beans rather
than programming the functionality into the bean itself
• The EJB container or IDE environment should supply tools to help in
generating the deployment descriptor
• There are many different settings that make up a deployment
descriptor that are relevant to session beans and they are
Writing the Deployment Descriptor (contd.)
• Bean home name : The nickname that clients use to look up for the
bean’s home object
• Enterprise bean class name : The fully qualified name of the
enterprise bean class
• Home interface class name : The fully qualified name of the home
interface
• Remote interface class name : The fully qualified name of the home
interface
Writing the Deployment Descriptor (contd.)
• Reentrant : Whether the enterprise bean allows reentrant calls, this
setting must be false for session beans, it applies for entity
beans only
• Stateful or stateless : Whether the session bean is stateful or
stateless session bean
• Session timeout : The length of time in seconds before a client
should time out when calling methods of a bean
Deployment Descriptor setting
Value
Bean home name HelloHome
Enterprise bean class name Com.session.helloworld.HelloBean
Home interface class name Com.session.helloworld.HelloHome
Remote interface class name Com.session.helloworld.Hello
Environment properties <empty>
Re-entrant false
Stateful or stateless STATELESS_SESSION
Session timeout 10 seconds
Deployment Descriptor Settings for HelloBean
Hello World Client source code
package com.session.helloworld;
import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
import java.util.Properties;
/*
This class is an example of client code which invokes methods on
a simple stateless session bean.
*/
public class HelloClient {
public static void main(String[] args) {
try {
/* Get System properties for JNDI initialization */
Hello World Client source code (contd.)
Properties props = System.getProperties();
/* Get a reference to the HelloHome Object – the factory for
Hello EJB Objects */
Context ctx = new InitialContext(props);
HelloHome home = (HelloHome) ctx.lookup("HelloHome");
/* Use the factory to create the Hello EJB Object */
Hello hello = home.create();
/* Call the hello() method, and print it */
System.out.println(hello.hello());
/* Done with EJB Object, so remove it */
hello.remove();
} catch (Exception e) {
e.printStackTrace();
} } }
Hello World client code explanation
• The client code performs the following tasks
• Looks up a home object
• Uses the home object to create an EJB object
• Calls hello() on the EJB object
• Removes the EJB object
The Basics of Stateful Session Beans
Stateful Session Beans
• Stateful beans are conversational beans because they hold
conversations with clients that span multiple method
invocations
• Stateful session beans store conversational state within the bean
• The conversational state is specific to a particular client
Characteristics of Stateful Session Beans
• Assume a situation where a number of clients having conversation
with stateful session beans running within a container
• The EJB container has only a finite amount of resources such as
memory , database connections, and socket connections
• If the number of clients that is trying to access the beans increases
the container could easily run out of resources
• In stateless session beans pooling is easy and a few beans can
service thousands of clients because there is no state to save
• In stateful session beans pooling is not simple
Characteristics of Stateful Session Beans (contd.)• When a client invokes a method on a bean, the client starts a
conversation with the bean and the conversational state stored
in the bean must be available for that same client on the next
method request
• Therefore the container cannot easily pool beans and dynamically
assign them to handle arbitrary client method requests as each
bean is storing state on behalf of a particular client
• This problem is similar to that of operating systems when the
physical memory is full and an application is to be executed the
hard disk is made as an extension of physical memory
Characteristics of Stateful Session Beans (contd.)
• When an application goes idle its memory can be swapped out from
physical memory and onto hard disk and when the application
becomes active again the related data is swapped in from the
hard disk into the physical memory
•The same scenario can be used with stateful session bean resources
• To limit the number of stateful session bean instances in memory the
container can swap out a stateful bean saving its
conversational state to a storage and this is called passivation
• After passivation the resources can be allocated for other clients use
Characteristics of Stateful Session Beans (contd.)• When the original client invokes a method the passivated
conversational state is swapped in to a bean and this is called
activation
• The activated instance is resuming its conversation from the point
where the original instance was passivated
• The passivation/activation process can create I/O bottleneck
• How to decide which beans to activate and which beans to passivate
• Most containers will employ a Least Recently Used (LRU) passivation
strategy which means to passivate the bean that has been
called the least recently
Characteristics of Stateful Session Beans (contd.)
• This is a good algorithm because remote clients have the habit of
disconnecting from the network leaving the beans stranded
without a client ready to be passivated
• Any bean involved in a transaction cannot be passivated until the
transaction completes
• If a client request comes in but that client’s conversation has been
passivated the container will activate the bean on demand
reading the passivated state back into the memory
• To serialize a bean the bean must extend java.io.Serializable
Characteristics of Stateful Session Beans (contd.)
• When a container passivates a bean it uses object serialization to
convert the bean’s conversational state into a bit blob and the
bit blob is written out to storage
• Activation reverses the process a serialized blob that had been
written to storage is read back into memory and converted to in
memory bean data
• The EJB container calls the ejbPassivate() method to give the bean a
chance to release the resources the bean held
• The ejbActivate() gives the bean a chance to restore the resources it
released during ejbPassivate()
A Simple Stateful Session Bean
• The bean is a counter bean and the bean will be counting up one by
one
• The current count will be stored within the bean and it will increment
as client request arrive
• This is a stateful bean and it will hold a multimethod conversation
with a particular client
• The remote interface difines a single business method count() which
is responsible for incrementing an integer member variable
called val
package com.session.count;
import javax.ejb.*;
import java.rmi.RemoteException;
/* These are CountBean's business logic methods. This interface is
what clients operate on when they interact with EJB objects. The
container vendor will implement this interface; the implemented
object is the EJB object, which delegates invocations to the
actual bean. */
public interface Count extends EJBObject {
/* Increments the int stored as conversational state */
public int count() throws RemoteException;
}
Count Bean remote interface source code
package com.session.count;
import javax.ejb.*;
/* Demonstration Stateful Session Bean. This Bean is initialized to
some integer value, and has a business method which increments
the value. This example shows the basics of how to write a
stateful session bean, and how passivation/activation works.
*/
public class CountBean implements SessionBean {
private transient SessionContext ctx;
/* The current counter is our conversational state. */
public int val;
/* Business methods Counts up */
Count Bean source code
public int count() {
System.out.println("count()");
return ++val;
}
/* EJB-required methods */
public void ejbCreate(int val) throws CreateException {
this.val = val;
System.out.println("ejbCreate()");
}
public void ejbRemove() {
System.out.println("ejbRemove()");
}
Count Bean source code (contd.)
public void ejbActivate() {
System.out.println("ejbActivate()");
}
public void ejbPassivate() {
System.out.println("ejbPassivate()");
}
public void setSessionContext(SessionContext ctx) { }
}
Count Bean source code (contd.)
Count Bean source code explanation
• The bean implements javax.ejb.SessionBean this means the bean
must define all methods in the SessionBean interface
• The ejbCreate() initialization method takes a parameter val, this is in
stark contrast to stateless session beans which never take
parameters in ejbCreate()
• The initialization method uses val as the starting state of the counter
• The val member variable obeys the rules for conversational state
because it is serializable and it will automatically be preserved
during passivation and activation
package com.session.count;
import javax.ejb.*;
import java.rmi.RemoteException;
/* This is the home interface for CountBean. This interface is
implemented by the EJB Server's glue-code tools - the
implemented object is called the Home Object, and serves as a
factory for EJB Objects. One create() method is in this Home
Interface, which corresponds to the ejbCreate() method in the
CountBean file.
*/
Count Home interface source code
public interface CountHome extends EJBHome {
/* This method creates the EJB Object. @param val Value to initialize
counter to @return The newly created EJB Object.
*/
Count create(int val) throws RemoteException, CreateException;
}
Count Home interface source code (contd.)
Count Home interface explanation
• The home interface shows how to create and destroy the Count EJB
object
• The home interface implements javax.ejb.EJBHome so it gets the
remove() destroy methods free
Deployment Descriptor setting Value
Bean home name CountyHome
Enterprise bean class name com.session.count.CountBean
Home interface class name com.session.count.CountHome
Remote interface class name com.session.count.Count
Environment properties <empty>
Re-entrant false
Stateful or stateless STATEFUL_SESSION
Session timeout 10 seconds
Max beans loaded at any time 2
Deployment Descriptor Settings for Count Bean
Count Bean’s deployment descriptor
• The Max beans loaded at any time descriptor restricts the maximum
number of beans loaded
• The container can load three beans at a time and the container will be
forced to passivate in order to reduce the number of beans in
memory
• The bean’s stateful nature is defined declaratively in the deployment
descriptor
• The bean is not declared stateful in the bean code itself because this
allows to easily switch from the stateful to staless paradigm and
back
package com.session.count;
import javax.ejb.*;
import javax.naming.*;
import java.util.Properties;
/*This class is a simple example of client code which invokes
methods on a simple Stateless Enterprise Bean. This create 3 EJB
Objects in this example, but we only allow the container to have 2
in memory. This illustrates how beans are passivated to storage.
*/
public class CountClient {
public static void main(String[] args) {
try {
/* Get System properties for JNDI initialization */
Count client source code
Properties props = System.getProperties();
/* Get a reference to the Home Object – the factory for EJB
Objects */
Context ctx = new InitialContext(props);
CountHome home = (CountHome) ctx.lookup("CountHome");
/* An array to hold 3 Count EJB Objects */
Count count[] = new Count[3];
int countVal = 0;
/* Create and count() on each member of array */
System.out.println("Instantiating beans...");
for (int i=0; i < 3; i++) {
/* Create an EJB Object and initialize it to the current count value */
Count client source code (contd.)
count[i] = home.create(countVal);
/* Add 1 and print */
countVal = count[i].count();
System.out.println(countVal);
/* Sleep for 1/2 second */
Thread.sleep(500); }
/* A call on count() on each EJB Object to make sure the beans
were passivated and activated properly */
System.out.println("Calling count() on beans...");
for (int i=0; i < 3; i++) {
/* Add 1 and print */
countVal = count[i].count();
System.out.println(countVal);
Count client source code (contd.)
/* Sleep for 1/2 second */
Thread.sleep(500); }
/* Done with EJB Objects, so remove them */
for (int i=0; i < 3; i++) {
count[i].remove();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Count client source code (contd.)
Count Bean’s client code description
• The client code performs the following steps
• A JNDI initial context is acquired
• The home object is located using JNDI
• The home object is used to create three different Count EJB objects
• Three different conversations are created and they simulate three
different clients
• The deployment descriptor limits the bean pool size to two beans so
during the previous step some of the three beans must have
been passivated and a message is printed during the
ejbPassivate() call back to show this
Count Bean’s client code description (contd.)
• When a call is made on the count() method of an EJB object the
container is forced to activate the instances restoring the
conversations to memory once again and a message is printed
during the ejbActivate() callback to show this
• Finally all the EJB objects will be removed
When are Stateful beans and stateless bean be used ?
• For stateless bean the EJB container is able to easily pool and reuse
beans allowing a few beans to service many clients
• When the same paradigm is used with a stateful beans the bean state
must be passivated and activated between method calls possibly
resulting in I/O bottlenecks
• A stateful session bean caches a client conversation in memory and
a bean failure may entail losing the conversation
• The largest drawback of statelessness is to push client specific data
into the stateless bean for each method invocation
When are Stateful beans and stateless bean be used (contd.)
• Most stateless session bean will need to receive some information
that is specific to a certain client such as a bank account number
for a banking bean
• The information must be resupplied to stateless beans each time a
client request arrives because the bean cannot hold any state on
behalf of a particular client
• If client specific data is passed as parameters into the bean’s method
performance degradation happens especially if the data being
passed is large
When are Stateful beans and stateless bean be used (contd.)
• Another way to get client specific data to a stateless bean is for the
bean to store data persistently on behalf of a client and get the
data from persistent storage by supplying an identifier
• If a business process span multiple invocations and require a
conversation then stateful model fits the best
• If the business process lasts for a single method call then stateless
bean suits the best
• Some sophisticated deployments have a combination of stateless
and stateful beans