Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Patterns for buildingfast and scalableEJB applications
Markus Voelter, MATHEMA [email protected]
Patterns written by Voelter, Wolff, Schmid
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Each pattern is a three-part rule, which expresses a relation between a certain context, a certain system of forces which occurs repeatedly in that context, and a certain software configuration which allows these forces to resolve themselves.
Jim Coplien
What is a pattern?
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
patterns have become part of the mainstream
patterns for software design
patterns for software architecture
organizational patterns
pedagogical patterns
What is a pattern?
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Long Transaction Problem: Long transactions occur
Many locks, bad performance
Solution: Use a Stateful Session Bean to collect that data Database work is done in the final method call
Drawbacks Probably database checks are needed to ensure validity of
transaction Isolation might be broken Optimistic locking i.e. lots of conflicts might occur
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Long Transaction II
Example: Shopping Cart Items added,
transaction commited at the end
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Process As Entity Bean
Problem: Business Process with complex state, very long run time and/or collaboration of multiple users Stateful Session Beans can not be shared and have a short
life time
Solution: Use an Entity Bean instead Can be shared and is persistent
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Process As Entity Bean Example
Example: Travel Expense Report Employee,
bookkeeper, boss etc. collaborate
Can take quite some time...
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Service Component Facade Problem: Transactions across Entity Bean methods and
collaborations between Entity Bean methods cannot be defined
Solution: Use a Stateless Session Bean that accesses the Entity Beans One Session Bean method calls multiple Entity Bean
methods Transactions and collaborations can be expressed
Original Facade pattern tries to hide complexity Here collaboration is expressed
Example: Transfer between accounts
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Service Component Facade Problem: Transactions across Entity Bean methods and
collaborations between Entity Bean methods cannot be defined
Solution: Use a Stateless Session Bean that accesses the Entity Beans One Session Bean method calls multiple Entity Bean
methods Transactions and collaborations can be expressed
Original Facade pattern tries to hide complexity Here collaboration is expressed
Example: Transfer between accounts
You can use Home Operations for this purpose
The Entity Beans might have only local interfaces
EJB 2.0 Note
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Service Component Façade II
S ession B ean
E ntity B ean I
E ntity B ean II
S ession B ean
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Type Manager
Problem: Entity Beans are expensive Concurrency, synchronization, lifecycle management Cannot be switched off if not needed
Solution: Session Bean that works directly on the database Data represented as Data Transfer Objects Primary Key used to identify entities Primary Key passed to every method
Example: Stock watch (get/set quote)
Drawbacks Container services for Entity Beans not used i.e. Container
Managed Persistence, optimizations for database access etc.
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Type Manager II
Entity-Version: Person p = home.findByPrimaryKey( aKey );p.setName( “Potter” );p.setFirstName( “Harry” );
Type-Manager Version: PersonManager pm = home.create();pm.setName( aKey, “Potter” );pm.setFirstName( aKey, “Harry” );
- or better –
pm.setNames( aKey, “Potter”, “Harry” );
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Event Listener
Problem: Mutual or circular dependencies are bad Reusability Maintenance and deployment problems How can lower layer communicate with higher layers?
Solution: Method call in one way, event communication back Message driven Beans (EJB 2.0) are not enough: no
methods, only events
Drawbacks Performance degradation: Cascade of events as result of a
method call
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Event Listener Example
Example: Customer must be notified about payment of order
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Relationship Service
Problem: Every Entity Bean must provide methods to access related entities Often changes to implementation and interface are needed
Solution: Externalize the relations into a Relationship Service Can store different types of relationships and attributes
Example: Implementation as Entity Bean using Bean Managed Persistence
Drawbacks Entities are not entirely self-contained
Depend on Relationship Service Explicit access to Relationship Service needed
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Relationship Service
Problem: Every Entity Bean must provide methods to access related entities Often changes to implementation and interface are needed
Solution: Externalize the relations into a Relationship Service Can store different types of relationships and attributes
Example: Implementation as Entity Bean using Bean Managed Persistence
Drawbacks Entities are not entirely self-contained
Depend on Relationship Service Explicit access to Relationship Service needed
EJB 2.0 entity bean relationshipsgo in this direction.
However, you cannot store additional information with them
EJB 2.0 Note
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Data Access Object Problem: Bean Managed Persistence leads to mix of business
logic and database access Beans become complex Hard to test Hard to adapt to different databases
Solution: Add a class to handle persistence Lifecycle methods call this class
Example: CustomerDAO Implements ejbCreate(), ejbStore(), etc. Includes the attributes
Drawbacks Component implementation is more complex
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Data Access Object Problem: Bean Managed Persistence leads to mix of business
logic and database access Beans become complex Hard to test Hard to adapt to different databases
Solution: Add a class to handle persistence Lifecycle methods call this class
Example: CustomerDAO Implements ejbCreate(), ejbStore(), etc. Includes the attributes
Drawbacks Component implementation is more complex
EJB 2.0 CMP has improved significantly – you will use it more often, so BMP-DAOs are less important.
EJB 2.0 Note
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Dependent Object
Problem: Entity Beans has fine grained internal structure Attributes form semantic groups Groups are not independent entities themselves
Solution: Partition the state of an Entity Bean into several dependent objects Each object represents a semantic group
Drawbacks Identification e.g. for deleting dependent objects is often
hard Compare values Use IDs invisible to client Work on complete list of dependent objects
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Dependent Object
Problem: Entity Beans has fine grained internal structure Attributes form semantic groups Groups are not independent entities themselves
Solution: Partition the state of an Entity Bean into several dependent objects Each object represents a semantic group
Drawbacks Identification e.g. for deleting dependent objects is often
hard Compare values Use IDs invisible to client Work on complete list of dependent objects
You may want to use Local Entity Beans in EJB 2.0.
Dependent objects can also be used as DTO‘s (see later), which is not possible with Local Entity Beans.
EJB 2.0 Note
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Dependent Object II
Example: Person and telephone numbers, Email addresses
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Wrapped Business Object
Problem: Complex Business Logic in beans Developing, testing or debugging requires deployment
Solution: Add a class to hold the business logic (Business Object) Bean delegates to Business Object Testing and debugging directly on Business Object
Example: Customer All calls delegated Wrapped Business Object is created in ejbLoad()/ejbCreate()
Drawbacks Additional class and interfaces (more complex)
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Business Component
Problem: Some EJBs are always used together as a group No formal grouping Clients must operate on many components
Solution: Provide a Business Component consisting of multiple EJBs internally Distributed and released as one subsystem Facade as single access point Facade might use Weakly Typed Interface
Example: Order Business Component contains Order, OrderBulkReader, OrderWebInfo, OrderItem, OrderInfo
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Business Component II
BusinessCom ponent
C om ponen t A
C om ponen t B
C om ponen t C
FacadeCom ponent
IF A
IF B
IF C
IF BusinessComponent
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Administratable Component
Problem: In addition to business logic, administrative, setup or diagnosis methods are also needed Component must include everything to work properly Clients should only be able to call business logic
Solution: Implement administration, setup and test but allow access only to administrators Remote interface as subclass of business and administrative
interface Additional Beans Probably GUI interface
Example: Logging, self-test, database table creation of an Order
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Administratable Component II
BusinessC om ponent
C om ponen t A
C om ponen t B
C om ponen t C
F acadeC om ponen t
IF A
IF B
IF C
IF BusinessComponent
A dm inC om p
IF Admin
C lien t A pp A dm in A pp
C om ponen tX
IF Admin
C lien tA pp
A dm inA pp
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Configuration Service
Problem: Related components usually have some aspect of their configuration in common Technical or functional Specifying these in the Deployment Descriptor is inefficient
and error prone
Solution: Provide a central Configuration Service Each component accesses it Also client can access it
Example: OrderConfigService (Currency, VAT rate, DataSources etc.) for Orders
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Request Hub Problem: Component must know which other component is
responsible for a specific task Independent evolution is hard Component must know other components' interfaces
Solution: Provide a central component which receives each request and forwards it to the correct receiver Can mask different communication protocols Parameter and data types can be adapted
Example: Generic Request Hub with configurable request handlers
Drawbacks If responsibilities change so must the hub
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Request Hub II
BusinessC om ponent A
BusinessC om ponent A
BusinessC om ponent A
H ub
BusinessC om ponent B
BusinessC om ponent C
send request to hub
introspects request,optionally transform s it,and perform s additionaltasks like logging,...
forwards request
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Roll-your-own Interception
Problem: Some aspects are not supported by the Container, but must be used in every Bean More complex access rules than EJB provides Performance measurements (method runtime)
Solution: Create an Interception interface Code generation to create wrapper Bean implementations
Calls pre- and postoperations Calls real implementation
Example: Generic Interceptor, Access control for Beans
Drawbacks Code generation is often complex
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Roll-your-own Interception II
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Roll-your-own Interception III
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Trader
Problem: Usually components are looked up by name not by what they provide Static, no adaptation to changing environment
Solution: Provide a Trader that does lookups by properties
Example: Printer lookup
Drawbacks Trader must find matches, lookup Home Interface i.e.
overhead Home Handle can be used instead
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Deferred Store Problem: Frequent database updates even though Entity Beans
do not change Performance problems
Solution: Only store the state in the database if it was changed Introduce a flag to keep track of changes
Solution if business logic is implemented: Provide class with private instance variables and public
access method Access methods change flags accordingly Business logic is implemented in subclass Business logic must use access method Thus flags will be changed
Example: Customer Flag per instance or per attribute
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Historized State
Problem: Old data must be kept Data of Entity Beans is usually deleted (ejbRemove())
Solution: Implement Entity Components in a way that data is kept instead of deleted or changed Timestamp or version must be introduced Deleted data is only marked as deleted
Example: Customer ejbCreate(), ejbRemote() ejbLoad(), ejbStore()
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Lazy State
Problem: Loading the state of complex Entity Beans takes a lot of time Lots of data is loaded Only parts are needed
Solution: Do not load the entire state in ejbLoad() Load the state on demand E.g. in accessor methods
Example: Purchases of a customer
Drawbacks Makes only sense if loading the complete data is much more
expensive then loading only parts One large database operation is replaced by multiple small
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Middle Tier Cache
Problem: Slow database connection (e.g. legacy system) can become a bottleneck Probably only parts of the database are used
Solution: Install a Middle Tier Cache Pre-loads data from backend Entity Beans use cache only Cache writes changes back Different implementations possible
Drawbacks In multiserver environments only one cache should exist or
synchronization must be dealt with
Examples: Bought tools
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Bulk Setter
Problem: Repeated invocations of setter methods are inefficient Remote communication, transaction and security handling
Solution: Provide an additional operation (Bulk Setter) that takes a group of attributes as parameters
Person: setPersonInput(name, firstName, dateOfBirth)
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Bulk Setter II Standard-Version:
public interface Person extends EJBObject { ... void setName(String name) throws RemoteException; void setFirstName(String firstName) throws RemoteException; void setDateOfBirth(Date dateOfBirth) throws RemoteException; ...}
Bulk-Setter-Version:
public interface Person extends EJBObject { ... void setPersonData(String name, String firstName, Date dateOfBirth) throws RemoteException; ...}
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Data Transfer Object (DTO) Problem: Repeated invocations of getter methods are
inefficient Remote communication, transaction and security handling
Solution: Add a class that contains all attributes that are usually read together Add a Factory method to the Entity Bean to read a Data
Transfer Object
Example: PersonValueObject Constructor, getter / setter
Drawback Bean internal data on the client
Changes are not detectable on the client Data Transfer Objects depend on Use Cases
Might change
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Data Transfer Object II Standard-Version:
public interface Person extends EJBObject { ... String getName() throws RemoteException; String getFirstName() throws RemoteException; Date getDateOfBirth() throws RemoteException; ...}
DTO-Version:
public interface Person extends EJBObject { ... void PersonData getPersonData() throws RemoteException; ...}
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Bulk Reader
Problem: Client must retrieve lots of entities (e.g. for display) Accessing each entity as an Entity Bean or through a Type
Manager is inefficient
Solution: Provide a Session Component with finder methods Use direct database access Return list of Data Transfer Objects
Example: Product: All products of a certain category
Drawbacks Changes in the entity structure affect the Entity Bean and
the Bulk Reader
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Bulk Reader
Problem: Client must retrieve lots of entities (e.g. for display) Accessing each entity as an Entity Bean or through a Type
Manager is inefficient
Solution: Provide a Session Component with finder methods Use direct database access Return list of Data Transfer Objects
Example: Product: All products of a certain category
Drawbacks Changes in the entity structure affect the Entity Bean and
the Bulk Reader
Can be implemented as Home Operations in EJB 2.0.
EJB 2.0 Note
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Combined DTO Problem: Client needs state of several entities
Accessing each entity requires several network hops and knowledge about the relationships among the entities
Solution: Implement a Session Bean that collect data from related Entity Beans and returns them as a Combined Data Transfer Object
Drawbacks Additional component Session Bean depends on Entities
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Combined DTO (II)
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Combined DTO (III)
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Hashtable DTO Problem: If you need many different Data Transfer Objects lots
of methods and classes must be implemented Use case changes means new Data Transfer Objects and
thus lots of implementation
Solution: Insert attributes as a name/value pair into a hashtable (Hashtable Data Transfer Object)
Example: Write: Data Transfer Object is scanned for keys and
attributes are set Read: All attributes are written into the Data Transfer Object
Drawback No type checking possible
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Server Side Iterator
Problem: The result of a query is usually a collection. If only a part is needed unnecessary data is transferred to the client
Solution: Create a Server Side Iterator. Client retrieves chunks of data Client requests more later On the client a class can hide these details Server Side Iterator keeps track of what has been requested
Example: Person. Additional classes on server and client
Drawbacks More complex to implement
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Entity Bulk Modification Problem: Updating a large set of entities using Entity Beans
leads to bad performance Primary Keys are retrieved Each database row is retrieved by the primary key
Solution: Use a Session Bean to modify the entities directly in the database Might be implemented with EJB 2.0 Home Interface methods
Example: Change wage of each employee
Drawbacks Might use lots of locks (performance) Cache problems (Entity Beans are caches) No database independence (even if using CMP)
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Entity Bulk Modification Problem: Updating a large set of entities using Entity Beans
leads to bad performance Primary Keys are retrieved Each database row is retrieved by the primary key
Solution: Use a Session Bean to modify the entities directly in the database Might be implemented with EJB 2.0 Home Interface methods
Example: Change wage of each employee
Drawbacks Might use lots of locks (performance) Cache problems (Entity Beans are caches) No database independence (even if using CMP)
Can be implemented as Home Operations in EJB 2.0.
EJB 2.0 Note
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Contents
1. Architecture2. Dependencies3. Internal4. Large Systems5. Persistence6. State Access7. Variability
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Attribute List
Problem: If additional data must be stored accessor methods must be added accordingly Implementation and interface affected
Solution: Provide an attribute list and generic methods setAttribute(name, value), getAttribute(name)
Example: Case in a hospital
Drawbacks Two model: Generic model for additional attributes, usual
getter/setter for rest Type checking hard / impossible Non-existing attributes might be accessed Persistence is hard
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Extension Interface
Problem: Beans evolve, interfaces change Old interfaces should be kept available New interface should be added
Solution: Separate the interface from the Component Component might be asked for supported interface Interface returned as result of method calls This interface can be used to access the component
Example: Termination of a case in a hospital
Drawback Must be built into initial version of the component Possible type cast problems
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Strategy
Problem: Some aspects of the Component's behaviour should be flexible Flexibility does not influence interface Should be configurable at Component installation
Solution: Use the original GoF Strategy pattern together with Java's dynamic class loading Class name in Deployment Descriptor Class loaded dynamically at runtime
Example: Notification about state change in a hospital case Email, JMS message, ...
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Strategy II
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
Weakly Typed Interface
Problem: New functionality requires changes to interface Clients must be recompiled Redeployment
Solution: Create a generic interface Generic specification of commands including parameters Reflective features to query the component interface must
be available
Example: Request class, mathematical service
Drawbacks Static type checks become impossible
Patterns for building fast and scalable EJB apps
Patterns for building fast and scalable EJB applications copyright © 2001, MATHEMA AG
The End!
Questions? Criticism? Opinions?
You might also want to have a look at the book:
Voelter, Schmid, Wolff Server Component Patterns – Component Infrastructures illustrated with EJBWiley, 2002