Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

Sun™

Push
J2EE your development
Best furtherusing
Practices Tech
Days

a Real-life Example.
Carol McDonald
Technology Evangelist
carol.mcdonald@sun.com

Sun™ Tech Days

1
Sun™
Push
eBay yourArchitecture:
development further How to Go… Tech
Days

From there… … to here?


Microsoft IIS J2EE™ Container
Web Container Services
Presentation Tier

Configuration
eBayISAPI.dll

Security
Logging
EJB™ Container

MSXML Business Tier

Integration Tier

 Monolithic  Layered
 Proprietary  Loosely coupled
 Modular
 Standards based

2
Sun™
Push
What yourIs
development
Needed… further Tech
Days

 Learning the technology is


not enough
 Industry best practices
 Proven solutions
 How to avoid bad practices?

3
Sun™

Push your development further
Core J2EE Patterns Tech
Days

 Collection of best practices and Patterns for


for J2EE™ architecture
 Also J2EE™ architecture bad practices and
refactorings
 Based on Sun Java Center Services
experience
 Proven solutions
 Reuse design
 Robust and scalable architecture
 Improve quality
 Flexibility and maintainability
 Create a common vocabulary
4
Sun™
Push your BluePrints
Java TMdevelopment further
Program Tech
Days

 http://java.sun.com/blueprints
 Java Technology Series
TM

books
– Designing Enterprise Applications
with the J2EE Platform, 2nd Edition
● Covers J2EE 1.3 platform features
TM

– Designing Web Services with the


J2EE Platform (available soon)
 Sample applications
– Java Pet Store Demo
– Java Adventure Builder Demo
– Concrete code for the BluePrints
guidelines
– Starting points for your applications

5
Sun™
Push your development further
Agenda Tech
Days

 Web Tier best practices


 EJB Tier best practices
 Persistence Options
 Container Managed Persistence
 J2EE Performance
 JMS Best Practices (depending on the time)

6
Sun™
Push your development further Tech
Days

Some Web Tier


Best Practices
and Patterns

7
Sun™
Push your development further
Layering Tech
Days

Web Tier or Client Presentation Layer

Data Transfer Objects


Network i.e. Business Data Values

EJB Session Beans Business Logic Layer


Service Layer

Entity Domain Layer


EJBs Persistent Entities

8
Sun™
Push your development
Rationale further
for Layers Tech
Days

 More flexible, extensible:


 Presentation Layers
 Frequent changes, design to be flexible
 Business Services
 Implement “use-cases”
 Public Service interface
 Interface should remain valid for changes in
presentation and data store
 Data Layers
 Fewer changes, designed to optimize data access

9
Sun™
Push your development
Model further
View Controller Tech
Days

 Model = business data and rules, shared by all clients


 Controller defines the application behaviour, interprets user
actions and maps them into actions performed on the model
 View = renders the contents of the Model

Thin Browser Client

HTTP Request HTML Page

Presentation Layer Controller View

Model Layer Problem Domain Services

Persistence Layer Enterprise Resources

10
Sun™
Push your development
Model further
View Controller Tech
Days

✗Separate:
●Model data

●Control

Request ●Presentation of view


Servlet
Controller

Forward Business
Event Event
Response

JSP Bean
View Model Model
Data

Client Web EJB Tier

MVC Pattern

11
Sun™
Push your development
Service to Worker further Tech
Days

= MVC Pattern with more detail


Command
Factory
3. Parse Request
5. Create
1. Request Front 4. Get cmd
Client Controller

6. Execute Command
2. Common logic Helper

8. Dispatch
10. Response 7. Business
View logic
Dispatcher

Servlet View
Helper
JSP Data
9. Get Data Bean
Java™ Objects
12
Sun™
Push
Useyour
andevelopment further
MVC Framework Tech
Days

 Use Struts, JSF, or Sun Java Studio ... application


framework
 Frameworks provide a skeleton which you can extend
 Faster, easier development of
 Request processing
 Response generation
 Improve
 Design

 Modularity
 Maintainability

13
Sun™
Push your development further
Struts MVC Framework Tech
Days

Form Bean Action


View 1 3
1
2
4
Action
ActionServlet
Model
(Controller)
5
Action
View 2

Struts-config.xml
........
Action
........
........

14
Sun™
Push your development
Struts and Core further
J2EE Patterns Tech
Days

Front Controller Command Model

Request Action Business


Action
Mapping Action Service
Servlet
(xml)

Client

Uses

Response

Action Action
JSP View
Forward Form

View Dispatcher View Helper


15
Sun™
Push your development
Ebay.com: further
Presentation Tier Tech
Days

Request Handler

Request
Intercepting
Filter
Front
Controller
Command ? Business
Service

Navigation and Dispatch

Client
Navigator Dispatcher

View Processor XML

Intercepting View Transformer Core J2EE


Filter Processor Helper XSL
Response Pattern
Strategy

16
Sun™
Business Delegate
Push your development further Tech
Days

 Client
independent from
ejb tier
 Ejb details
hidden
 Mock objects can
be used to test
client w/o ejb tier

17
Sun™
Push your development
Ebay.com: further
Presentation Tier Tech
Days

Request Handler Service Interface

Request
Intercepting Front Business Business
Command
Filter Controller Delegate Service

Navigation and Dispatch

Client Service
Locator
Navigator Dispatcher

View Processor XML

Intercepting View Transformer Core J2EE


Filter Processor Helper XSL
Response Pattern
Strategy

18
Sun™
Push
Cacheyour development further
for Performance Tech
Days

 Some things can be cached and shared, use a


singleton:
 InitialContext object (JNDI object used for lookups)
 Anything retrieved from JNDI, EJB Home interfaces
 Repeated lookups can be expensive! Use Service Locator
Pattern
 Some things are user specific, cached in session:
 Cache search results when you are only displaying a few
at a time (static data)
 Value List Pattern

19
Sun™
Push your development
Service Locatorfurther
Pattern Tech
Days

DON'T DO
EJB JMS EJB JMS
Client Client Client Client
Service
Locator

JNDI EJB JDBC


EJB JDBC Client
Client
Client Client

JNDI

Repeated lookups can be expensive!


Use the Service Locator Pattern to
Cache references obtained by JNDI lookups
(ejb references, datasources, jms connection)

20
Sun™
Push your development further
ServiceLocator code Tech
Days

01 public class ServiceLocator {


02 private InitialContext ic;
03 private Map cache;
04 private static ServiceLocator me;
05
06 private ServiceLocator() {
07 ic = new InitialContext();
08 cache =new HashMap();
09 }
10 public static ServiceLocator getInstance() {
11 if (me == null) {
12 me = new ServiceLocator();
13 }
14 return me;
15 }

21
Sun™
Push your development further
ServiceLocator code Tech
Days

01 public EJBHome getRemoteHome(String jndiHomeName, Class className){


02 EJBHome home = null;
03 if (cache.containsKey(jndiHomeName)) {
04 home = (EJBHome) cache.get(jndiHomeName);
05 } else {
06 Object objref = ic.lookup(jndiHomeName);
07 Object obj = PortableRemoteObject.narrow(objref, className);
08 home = (EJBHome)obj;
09 cache.put(jndiHomeName, home);
10 }
11 return home;
12 }
15

22
Sun™
Push your development
Client code further Tech
Days

01 ServiceLocator serviceLocator =
02 ServiceLocator.getInstance();
03 try {
04 ProjectHome projectHome =(ProjectHome)
05 serviceLocator.getHome(“ProjectHome.class”);
...

23
Sun™
Push
Tipsyour
fordevelopment
Servletfurther
Performance Tech
Days

 Don't store a lot of data in the HTTP


Session
 Remove servlet sessions when they
are no longer needed:
 In logoff call session.invalidate()

24
Sun™
Push your development
Servlet Tips further Tech
Days

 DO use high performance J2EE


design patterns
 MVC, Service Locator
 DON’T hold resources – explicitly
free them

25
Sun™
Push
Tipsyour
fordevelopment
JSPs further Tech
Days

 Avoid scriptlets in JSP


 Use JSTL (JSP 2.0 Standard Tag Libraries):
 <c:forEach var="item" values="${cart}">
 Pass data to JSP in Servlet request object not
session
 If JSP does not use the HTTP session
 Use <%page session="false"%> to prevent
HTTP Sessions from being automatically created

26
Sun™
Push your development further Tech
Days

Some EJB Tier


Best Practices
and Patterns

27
Sun™
Push
Do your
youdevelopment
need EJBs?further Tech
Days

 Do you need declarative


transactional support?
 Do you need to distribute your
business logic?
 Do you need JMS, JAX-RPC, RMI?
 Do you need to support multiple
client types?
 Do you need method-level security
on your objects?
 Do you need Clustering for Scalability?
28
Sun™
Push your development
Architecting further
Applications Tech
Days

ebay Case Study

 Functional requirements captured


via use-cases
 Use-cases implemented using MVC &
Command design patterns
 Implement Business Logic as Services
 Verbs in use cases help define services
 Noun in use cases help define business data
objects

29
Sun™
Push
ebay yourUse
development
case further
realization Tech
Days

ebay Case Study View Items

View Items
by category

Any User

Any user can view auction


items by category

30
Sun™
Push
View yourItems
development further Requirements
Design Tech
Days

ebay Case Study


Centralize
Request Hndlg

Convert to
Biz Command
Assemble
Data

Use case
Biz logic
Retrieve
Data by category

31
Sun™
Push
View yourItems
development further
Design Tech
Days

ebay Case Study


Front
Controller

Transfer
Action Object Transfer
Command Object
Assembler

Business Session Value List


Delegate Facade Handler

Service Data Access


Locator Object

32
Sun™
Push yourApplication
Core development further
Design Patterns Tech
Days

Ebay Case Study Business Logic & Data Integration


Presentation
Messaging Fabric & Persistence

Request Response BUSINESS


SERVICE
FACADE

FRONT
VIEW
CONTROLLER

DATA
MODEL Value List Handler ACCESS
OBJECT

COMMAND DATA
TRANSFER DATA
object TRANSFER
OBJECT
OBJECT

WEB Tier SessionEJB

Servlet Java™ Objects


JSP Session EJB
33
Sun™
Push
Data your developmentObject
Transfer further Tech
Days

Client
Object EJB

Network
boundary
GetCity()

GetState()
DON'T DO
Before GetZipCode()
too much network traffic

A Data Transfer Object encapsulates


a set of data values to return to the
Client Item Info EJB client in one network transfer
Object Data Transfer Object

GetItemInfo()

Return DTO

GetCity()
After DO
GetState()
Reduce network traffic
GetZipCode() with Data Transfer Object
Network
boundary

34
Sun™
Push yourApplication
Core development further
Design Patterns Tech
Days

Presentation Business Logic & Data Integration


Messaging Fabric & Persistence

Request Response BUSINESS


SERVICE
FACADE

FRONT
VIEW
CONTROLLER

DATA
MODEL Value List Handler ACCESS
OBJECT

COMMAND DATA
TRANSFER DATA
object TRANSFER
OBJECT
OBJECT

WEB Tier SessionEJB

Servlet Java™ Objects


JSP Session EJB
35
Sun™
Push
Data yourAccess
development further
Object Tech
Days

Use DAO for read-only tabular access to a large set of data,


when query results are large and short-lived

BusinessObject DataAccessObject DataSource


Uses Encapsulates

Use Data Access Objects to


encapsulate data-access logic
creates/uses -provides a simplified interface for
performing complex JDBC
operations
-allows decoupling of data-access
optimizations
obtains/modifies TransferObject

36
Sun™
Push your
EJB Tierdevelopment
patterns further Tech
Days

Data Access Object (DAO)

public class FacadeEJB implements SessionBean {


protected EbayDAO dao;
public void ejbCreate() {
try {
dao = EbayDAOFactory.getDAO();
} catch (EbayDAOSysException se) {
throw new EJBException(se.getMessage());
}}

public ListChunk getItems(String categoryId,
int startIndex, int count, Locale locale) {
try {
return dao.getItems(categoryId, startIndex, count, locale);
} catch (EbayDAOSysException se) {
throw new EJBException(se.getMessage());
}}
…. }
37
Sun™
Push yourApplication
Core development further
Design Patterns Tech
Days

Presentation Business Logic & Data Integration


Messaging Fabric & Persistence

Request Response BUSINESS


SERVICE
FACADE

FRONT
VIEW
CONTROLLER

DATA
MODEL Value List Handler ACCESS
OBJECT

COMMAND DATA
TRANSFER DATA
object TRANSFER
OBJECT
OBJECT

WEB Tier SessionEJB

Servlet Java™ Objects


JSP Session EJB
38
Sun™
Push
Valueyour development
List Handlerfurther Tech
Days

 For querying, filtering, and


Interface
ValueListIterator displaying large amounts
+GetSize():int
of data:
+getCurrentElement():Object
+getPreviousElements(count:int):List
 Value List Handler handles
+getNextElements(count:int):List the search, can cache results
+resetIndex():void and provides a traversable result
set

<<List>>
Client ValueListHandler ValueList TransferObject

DataAccessObject

39
Sun™
Push your development
Example CachingfurtherResults Tech
Days

Client Stateful DataAccessObject


Session
Create
ValueListHandler
ValueListiterator ValueList

Execute Search Execute Search

Create
Return Sub List Return Value List

Get Next
Get Sub-list
Return Sub-list

Get Previous Get Sub-list


Return Sub-list

Get Current
Get Current
Return Value Object

Get Size
Get Size
Return Size

40
Sun™
Push your development
Returning Searchfurther
Results Options Tech
Days

 ValueList Handler as a Stateful Session


EJB caches search results, and returns
sub list
 ValueList Handler as Stateless Session
EJB:
 Select * FROM item WHERE id=?
LIMIT [count] OFFSET [startIndex]

 Instead of Value list could use JDBC 2.0


scrollable ResultSet but keeps JDBC
data source connection open ! (J2SE 1.5
will have disconnected scrollable ResultSet)
41
Sun™
Push your development
Stateless further
Example Tech
Days

Client Stateless DataAccessObject


Session
ValueListHandler
Create ValueListiterator

Execute Search (index, count) Execute Search (index, count)


Create ValueList

Return Sub List Return sub List

Execute Search (index+count, count)


Execute Search (index+count, count)
Create

Return Sub List Return sub List

Select * FROM item WHERE id=?


LIMIT [count]OFFSET [startIndex]

42
Sun™
Push yourApplication
Core development further
Design Patterns Tech
Days

Presentation Business Logic & Data Integration


Messaging Fabric & Persistence

Request Response BUSINESS


SERVICE
FACADE

FRONT
VIEW
CONTROLLER

DATA
MODEL Value List Handler ACCESS
OBJECT

COMMAND DATA
TRANSFER DATA
object TRANSFER
OBJECT
OBJECT

WEB Tier SessionEJB

Servlet Java™ Objects


JSP Session EJB
43
Sun™
Push your development
Session Facade further
pattern Tech
Days

Session Bean Entity


Bean 1
Entity Bean
Plain Java™ Object 2. getData() 2. getData()
Data
Entity
Access
Bean 2
Object 1
Client Session
1. doThis(...) Facade
Session Data
Bean Access
Object 2

3. process
Java™
 Use the Session Facade: Object

 provide a simple interface to a complex subsystem of


enterprise beans
 Enforce a clear and strict separation of business logic from
presentation and data logic

44
Sun™
Push
Useyour
thedevelopment
Session further
Facade pattern Tech
Days

To Execute complex use cases in a single network call to


reduce network overhead

Direct Bean Access


Don’t: EJB
Client

Network

Direct Entity Bean access results in excessive network overhead


and multiple transactions

Do:
EJB
Network F
a
Client c
a
d
e

Direct Entity Bean access results in excessive network overhead


45
Sun™
Push
Use yourthe
development
SessionfurtherFacade Tech
Days

To group finer grained calls to local entity beans

Local vs. Remote Interfaces


Remote Interfaces Local Interfaces

EJB EJB EJB EJB


client Object client Object

Network

Pass by Value: Pass by Reference:


Serialize/deserialize Better performance
method parameters

46
Sun™
Push your development
Design your localfurther& remote EJBs Tech
Days

Use Session Facade to group finer grained calls to local EJBs


in a Coarse Grained Interface
Java
Client

WebComp
onent
Remote WebComp
Facade
WebComp
onent Determine which EJBs
onent will be collocated within same
Business
Delegate
VM

LineItem
Relationship Admin
Remote CreditCard
Reference Facade Purchase Order

Address

47
Sun™
Push
Useyour
thedevelopment
Session further
Facade Tech
Days

To group related updates into container managed transactions

Application Server DataBase Server


TX_REQUIRED TX_REQUIRED
or JMS Provider
Check Out Update
Inventory Inventory
Facade Resource
Client Order
createOrder

Commit
or
Start Prepare rollback

Transaction Create context x


Manager Add to context x Transaction
Add to context x context

Check context
x to see if
updates will work

48
Sun™
Push your development
eBay.com: further
Business Tier Tech
Days

ebay Case Study


Dispatch Persistence

Application Domain
DAO Data
Controller Store
Source

Business
Command Context Logic/Data
Object
Application
Service
Business
Facade Object

Transfer
Object
Transfer Value
Object List
Core J2EE
Assembler Handler
Pattern
Strategy

49
Sun™
Push your development
Session EJB tips further Tech
Days

 Remove stateful session beans when


finished (user logs out)
 Bean.remove()
 Limit size of objects stored in session
beans due to memory cost and I/O for
passivation

50
Sun™
Push your development
Stateless further
or Stateful Session EJB? Tech
Days

 Stateless session beans are pooled and


can service multiple clients
 give best performance
 Stateful store conversational state=1 per
client (are activated and passivated)
 For Performance Strive for Statelessness
when application has a high number of
users
 convert Stateful to stateless by adding parameters
to the bean methods that hold the extra state

51
Sun™
Push your development further Tech
Days

Persistence
Best
Practices

52
Sun™
Push
Data yourAccess
development further
Options in J2EE: Tech
Days

 Object-oriented (transactional) data model


 EJB Container Managed Persistence
 Great choice for ease and performance
 JDO
 Tabular access
 EJBs should not be simple wrappers on
database data rows; they should have business
logic. To simply access data, use Plain JDBC
encapsulated in a DAO
 Non-relational, non-object data access,
Legacy systems, CRM, SAP...
 Use J2EE Connectors
53
Sun™
Push
BMP yourvs.
development
CMP further Tech
Days

BMP JDBC JDBC SQL Bean


Bean SQLJ Driver State

Database
EJB Container
1) Bean provider manages State and Data consistency
2) Bean provider handles relationships and OR Mapping

CMP JDBC JDBC SQL Bean


Bean SQLJ Driver State
Persistence Database
EJB Container Manager

1) Container manages State and Data consistency


2) Container/PM provides concurrency, relationships and OR Mapping

54
Sun™
Push
CMP your2.0
development
Entity further
Beans Tech
Days

Entity Bean is now an abstract class, container extends it

<<interface>>
java.io.Serializable

<<interface>>
javax.ejb.EnterpriseBean

<<interface>>
javax.ejb.EntityBean

CMP Entity Bean abstract class You (bean provider)


(Contains data handling logic) write this code.

CMP Entity Bean subclass Container provides


(Contains persistence logic) this class.

55
Sun™
Push your development
Container further
Managed Relationships Tech
Days

Address
Order
Local Entity
1
Shipping Address

1 Local Entity
Client OrderBean Product
1 1
LineItems ProductOrdered
M M
OrderHome LineItem
Local Entity
EJB Tier

56
Sun™
Push your development
Accessors further and
for CMP CMR Tech
Days

public abstract class OrderBean implements EntityBean {

private EntityContext context;

//access methods for cmp fields

public abstract String getOrderID(); //primary key


public abstract void setOrderID(String id);
. . .
//access methods for cmr fields

public abstract Collection getLineItems();


public abstract void setLineItems(Collection lineItems);

57
Sun™
Push
CMP your2.0
development further
Relationship Handling Tech
Days

 In CMP 2.0, you declare fields and


relationships in deployment descriptor
 Container generates all the necessary code
<ejb-jar>
<enterprise-beans>
... define your enterprise beans ...
<cmp-field> elements represent container-managed
persistent fields
</enterprise-beans>
<relationships>
... define EJB relationships ...
</relationships>

58
Sun™
Push your development
Example further
CMP Wizard Tech
Days

59
Sun™
Push your development
Advantages of further
CMP 2.0 Tech
Days

for developer
 container manages the persistence and
the relationships, not you!
 No SQL or persistence logic in source code
 Freedom from maintaining interactions
with the data store
 EJB™ Query Language (EJB QL)
 Portable code

60
Sun™
Push your development
Advantages of further
CMP 2.0 Tech
Days

for Container
 Optimization is possible because
persistent fields are only accessible
via get and set methods
 Containers knows
 Which field is being accessed
 Whether or not field is in a relation
 Whether of not there is a transaction
 What's in cache
 The current clustering environment
 Can optimize based on above

61
Sun™
Push
Some your CMP
development further
Optimizations Tech
Days

 Aggressive Loading
 Loading data for Entities in a relationship in the
same query
 Lazy Loading
 Deferring loading of any data until it is accessed
 Dirty Writes
 Only update data which has been changed
in the database

62
Sun™
Push
CMP: yourStandard
development further
Vs. Tech
Days

Vendor Specific Features

 Standard features
 Declarative specification of:
 Persistent attributes, abstract schema, relationships,
queries for finder/select methods(via EJBQL),
transactional attributes
 Vendor specific
 Tools, concurrency and consistency
semantics, caching semantics, performance
and usability

63
Sun™
Push your development
Pessimistic further
Locking Tech
Days

Serialized Access to same Bean

C1 C2
Time State in
Database
1000 Begin Txn
1000
read initial
balance w/Lock Begin Txn
.. read initial
balance += 1000 balance w/lock
(blocks ..)
..
2000 2000 Commit

2000 unblocks

balance +=
3000 3000 1000

Commit

The entity blocks until previous transaction commits


64
Sun™
Push your development
Optimistic furtherWith
Locking Tech
Days

“ Update-conflict” Detection
Concurrent Access to same Bean

C1 C2
Time State in
Database
1000 Begin Tx Begin Tx Retry
1000 1000
Select initial Select initial
balance balance
..
2000
..
balance += 1000 balance += 1000
update
2000 2000 ..
Commit update 3000
Exception

..
3000 Commit

Concurrent Access to same Bean (same Primary Key)


Lock obtained at update time, conflict detection

65
Sun™
Push
Usageyour development
Guidelines further Tech
Days

 Pessimistic  Optimistic
 Recommended for  Use when
consistency when concurrent
concurrent updates access is mostly
would be frequent reading
 For scalability
 Requires
exception
SunOne deployment descriptor handling
<consistency>
<lock-when-loaded/>
</consistency>

66
Consistency Levels
further in CMP
Sun™
Push your development Tech
Days

 Chose optimistic concurrency for


CMPs with “read-mostly” access
 Tradeoff between performance
and consistency in transactions

67
Consistency Levels
further in CMP
Sun™
Push your development Tech
Days

 Sun Java System Application Server 7


supports these consistency levels
(in sun-cmp-mappings.xml)
– Check-modified-at-commit = most optimistic
– Check-all-at-commit
– Lock-when-modified
– Lock-when-loaded = most pessimistic
– None

68
Sun™
Push your development
Database further Modes
Isolation Tech
Days

 Choose the lowest cost database


transaction isolation level that avoids
corrupting the data.
 Transaction levels in order of
increasing consistency and cost are:
 Read Uncommitted
 Read Committed
 Repeatable Read
 Serializable
 consider READ COMMITTED with
optimistic locking
69
Sun™
Push your development
Entity Bean Tips further Tech
Days

 Do not use EJB entity beans for batch


loading or queries that return large result
sets. Use Data Access Objets
encapsulating JDBC
 Use CMP rather than BMP entity bean
when possible
 Do not call EJB entity bean get & set
methods from client
 Wrap with session beans to provide course
grain access and single transaction context

70
Sun™
Push your development further Tech
Days

J2EE Performance
Tips:
how to get the most
out of your Application
Server

71
Sun™
Push your development
Application further
Resources Tech
Days

 Standard application resources:


 CPU
 Memory
 I/O
 Network
 Database

72
Sun™
Push
Tune yourApp
development
Serverfurther Tech
Days

 EJB Bean Cache and Pools


 JDBC
 connection pools
 Prepared statement cache size
 JVM Heap size
 (go to garbage collection Performance session)
 Correct settings depend on application,
test to determine sizes

73
Sun™
Push
Tune yourKey
development further
Container Parameters Tech
Days

 Stateful session bean and Entity bean


cache
 Cache = EJB instances with state
 Minimizes activation and passivation
 Stateless session and Entity bean pools
 Pool = EJB instances with no assigned state
 Minimizes creation and initialization

74
Sun™
The EJB
Push your Container
development further Tech
Days

Pooling and Caching of EJB Instances


Allow for reuse of bean
instances
Pooling Caching
objective: minimize creation + activation /
initialization passivation

for message-driven yes no


for stateless session yes no
for stateful session no yes
for entity beans yes yes

75
Sun™
Push your development
Entity Bean further Tech
Days

EjbActivate()

Does
not exist
NewInstance()
Bean pool size setEntityContext() unsetEntityContext()
minimizes creation
and initialization
pooled
ejbFind()
EJB
Instance
ejbCreate() ejbRemove()
ejbPostCreate()
ejbActivate() ejbPassivate()
Bean cache size
minimizes activation ready

and passivation ejbLoad() EJB EJB ejbStore()


Object Instance

business method
76
Sun™
Push your development
Entity Bean Cachingfurther Tech
Days

 Commit Option A
 At the end of the transaction, the instance stays
ready (cached) and the instance state is valid
 Commit Option B
 At the end of the transaction, the instance stays
ready (cached) but the instance state is NOT
valid ( ejbLoad will be called )
 Commit Option C
 At the end of the transaction, neither the instance
nor its state is valid (passivated)
 Best Option: Usually B, if Entity will be
accessed again. do profiling with your
77 application on your app server
Sun™
Push your development
Stateful Session further
Bean Tech
Days

Bean cache size


minimizes activation does not
and passivation exist

1) newInstance() ejbRemove()

2) setSessioncontext()
removal time out
3)ejbCreate() ejbPassivate()

Method-ready

EJB EJB passive


Object Instance

business method EjbActivate()

78
Sun™
Stateless
Push Session
Bean
your development further Tech
Days

and Message Driven Bean

Bean pool size


minimizes creation
and initialization does not
exist

1) newInstance()

2) setSessioncontext() EjbRemove()

3)ejbCreate()

method-ready
pool
Business method
EJB
Instance

79
Sun™
Push
Theyour development
Sun's EJBfurther
Container Tech
Days

Cache Tunables
 commit-option (B|C) (entity beans)
 Max-cache-size (0 = unbounded)
 cache-idle-timeout-in-seconds
(0 = indefinitely)
 removal-timeout-in-seconds
(stateful session)
 Adjust cache size: Increase until a good cache hit
rate is reached
– For fine tuning, understand a bean’s usage
pattern (reads, updates, creates, removes ...)

80
Sun™
Push
Theyour development
Sun's EJBfurther
Container Tech
Days

Pool Tunables
 steady-pool-size (not for message-
driven)
 max-pool-size (0 = unbounded)
 pool-idle-timeout-in-seconds
(0 = indefinitely)
 Adjust a bean’s pool size:
– Increase when observing excessive creation
and deletion of bean instances
– Decrease when accumulating a large number
of instances in pool
81
Sun™
Push
Theyour development
Sun's EJBfurther
Container Tech
Days

Configuring Pool and Cache


 Per bean: in ejb module’s sun-ejb-
jar.xml
– <bean-pool> and <bean-cache>
 Global defaults: in server instance’s=
server.xml
– <ejb-container> and <mdb-container>

82
Sun™
Push
JDBC your development
Tips further Tech
Days

 Select a good Thin JDBC driver


 Tune connection pool size
 Close resources as soon as you’re done
with them (in finally)
 E.g. Statements, Connections, ResultSets…
 Use JDBC’s PreparedStatement when
possible:
 stmt = connection.prepareStatement(..);
 Tune statement caching
 Turn off Auto-Commit
 Group updates into a transaction
83
Sun™
Push your development
Database further
Statement Caching Tech
Days

 Statement caching
– 15–25% Performance improvement
– Requires knowledge of database specific
properties, i.e. Oracle
<jdbc-connection-pool datasource-classname=
"oracle.jdbc.pool.OracleDataSource" ...>
<property name="ImplicitCachingEnabled"
value="true"/>
<property name="MaxStatements" value="200"/>
</jdbc-connection-pool>

84
Sun™
Push your development
Database further
Performance Tech
Days

 Common performance bottleneck


 Typical problems:
 primary key to big (use integer)
 Inefficient queries - sending SQL data
that asks the database to do more work
than necessary
 run the SQL through the EXPLAIN SELECT command
 index the columns in your WHERE clauses
 Large Data Sets - processing large sets
of data in ResultSets

85
Sun™
Push your developmentTips
Performance furtherSummary Tech
Days

 Tips for better performance


 Tune app server and infrastructure
 Container Caching and Pools
 Database access
 Use JDBC for:
 Batch loading: session bean or message bean
 Large result sets: value list handler
 Use CMP rather than BMP Entity Beans
 Use right isolation level and database
transactional control (locking)

86
Sun™
Push
EJB your development
Tips Summaryfurther Tech
Days

 EJB Container Services – use appropriately for:


 Distributed transaction management
 Robust security service
 Resource management (threads, sockets, database connections)
 Container persistence
 Remote accessibility
 Dispatch and life-cycle management.

87
Sun™
Push your development
Manage further
Expensive Resources Tech
Days

 Cache “EJB homes”


 Cache data sources
 Minimize use of HTTP sessions
 Release database connections
 Remove unused stateful session beans
 Use local Interfaces [Session Facade]

88
Sun™
Push your development
Design Patterns further
can Tech
Days

Significantly Help Performance

 Session Facade
 Service Locator
 Value List Handler
 Data Transfer Object

89
Sun™
Push your development further Tech
Days

Some JMS
Messaging,
J2EE Best
Practices
90
Sun™
Push your
JMS development further
Communication Tech
Days

JMS Provider
Producer Destination Consumer

 Loosely coupled:
– Producer doesn't need to know consumers or consumer method
arguments
 Reliable:
– Message is stored until it can be delivered
 Asynchronous
– Producer is not blocked, consumer does not have to be available

91
Sun™
Push
Useyour
JMSdevelopment
for further Tech
Days

 Asynchronous Interaction
 Concurrent processing
 Scalability
 Batch processing
 Broadcasting messages to multiple
recipients
 Reliable messaging
 Messaging with Transaction Support
 Loose Coupling

92
Sun™
Push your development further
Message-Driven Bean Tech
Days

Concurrent Asynchronous Processing


 High Scalability, High Throughput
 MDB instances are pooled by the container
 Allow for asynchronous concurrent message consumption
from the same destination

Container
JMS Container
Provider
Desti MDB
Msg-
Consume MDB
Queue
n- Consumer driven
Instances
Instances
r
ation Bean
Msg-Driven
Bean Class

93
Sun™
Push yourFacade
MDB development further
Pattern Tech
Days

Mailer MDB

EJB
Asynchronous
Message
LineItem Tier
Delivery Order Entity
Card
Approval 1:m
Entity
MDB Purchase
Order Entity

Address
Entity

 Use the MDB Facade:


 provide a simple asynchronous interface to a complex
subsystem of enterprise beans
94
Sun™
Push
JMSyour development further Tech
Days

 Use JMS for loosely coupled


applications that need reliable,
scalable document oriented
message exchange
 Including Message-Driven
Beans and JMS in your J2EE™
application can greatly increase
performance, robustness, and
efficiency

95
Sun™
Push
XML yourMessage
development further
Facade Tech
Days

EJB Architectural Pattern


Entity
Bean
XML XML Messaging Facade Java™
msg Value
Message Objects Stateless Entity
External JMS
Session
Driven Bean
Application Queues Bean EJB
Entity
Asynchronous Synchronous Bean

Example implementation of XML interaction model


on top of Java™ interaction model

Ref JavaOne
96
Sun™
Push
Tips your
fordevelopment further
XML messaging Tech
Days

 Inside your Application don’t overuse XML


 Parsing and processing can cause a performance
hit
 Use XML for messages between
systems…
 Within a system just use java data objects
 Convert the data from XML into a Java™
class as soon as possible
 Can use JAXB for this
 Use XML mainly for transmission

97
Sun™
Push your development further
Asynchronous Web Services Tech
Days

Web Message Business Domain EAI Resource RDBMS


container Services Services Objects Adapters
Soap Data
Base
Web Session Entity
component MDB DAO
EJB EJB

Entity Connector Legacy


Business
MDB Session Systems
Document EJB EJB

MDB

ERP

98
Sun™
Push your development
FUTURE: further
JBI and J2EE Tech
Days

Web App.
EJB JBI BP Module
Module
Module (WS-BPEL and
(JSP/Servlet
(EJB API) WSDL APIs)
API)
208 “Machine”
SPI

Normalized Message “Bus”

208 “Binding”
SPI
Binding Framework

WS-I JMS JCA EDI VAN

SOAP MQ EIS resource AS1/AS2

99
Sun™
Push your development further Tech
Days

Tools
Summary
Resources

100
Sun™
Push your
Use development further
Tools Tech
Days

 Use IDE or Xdoclet to keep EJB class,


home interfrace, remote interface
consistent
 Use Junit for Unit testing
 Use Ant to automate deployment and
testing
 All of these are provided with
Sun Java Studio

101
Sun™
Push your development further
Summary Tech
Days

 J2EE Patterns and Best Practices


are proven solutions
 Reuse design
 Robust and scalable architecture
 Improve quality, performance
 Flexibility and maintainability
 Java BluePrints Program
TM

 http://java.sun.com/blueprints
 Designing Enterprise Applications
with the J2EE Platform, 2nd Edition

102
Sun™
Push your development further
Resources: Tech
Days

http://java.sun.com/blueprints Java Performance Tuning

103 J2EE Performance Testing


Sun™
Push your development further Tech
Days

Carol McDonald
Technology Evangelist
carol.mcdonald@sun.com

Sun™ Tech Days

104

You might also like