You are on page 1of 98

Sun™

Push
J2EE your development
Best furtherusing
Practices Tech
Days
Real-life Examples.
Sridhar Reddy
Technology Evangelist
sridhar.reddy@sun.com

Sun™ Tech Days

1
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?

2
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

3
™ Sun™
Push
Core yourJ2EE
development further
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
 JavaTM Technology Series
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 fall 2003)
 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 Servlet Presentation of view

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

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

 Faster, easier development of


 Request processing
 Response generation
 Use Struts, JSF, Sun ONE ... application framework

13
Sun™
Push your development
Struts Framework further 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


XSL Core J2EE
Filter Processor Helper
Response Pattern
Strategy

16
Sun™
Push your development further
Business Delegate 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


XSL Core J2EE
Filter Processor Helper
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
 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 Locator further
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 = Collections.synchronizedMap(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
Servlets further Tech
Days

 Servlets are Multithreaded


 Avoid use of shared modified class variables
 Synchronize only small blocks in code

 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

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 yourTransfer
developmentObject
further Tech
Days

Client
Object EJB

Network
boundary
GetCity()

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

A Da ta Tra ns fe r Obje ct e ncaps ula te s


a s e t of da ta va lues to re turn to the
Client Item Info EJB
Object Data Transfer Object clie nt in one ne twork tra ns fe r
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 { DAOs


protected EbayDAO dao; as the app is designed for
public void ejbCreate() { different databases
try {
dao = EbayDAOFactory.getDAO();
The name of the particulary
} catch (EbayDAOSysException se) {
DAO class is lookup in the env.
throw new EJBException(se.getMessage());
settings given in the deploy-
}}

ment descriptor
public ListChunk getItems(String categoryId,
int startIndex, int count, Locale locale) { Reflection is used to instantiate
try { a concrete instance of the class
return dao.getItems(categoryId, startIndex, count, locale);
} catch (EbayDAOSysException se) {
throw new EJBException(se.getMessage());
}} Example: EbayDAOFactory
…. }

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

Interface
 For querying, filtering, and
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
ValueListHandler
1: Create ValueList
ValueListiterator

2: Execute Search
2.1: Execute Search

2.1.1: Create

Return Sub List Return Value List

3: Get Next
3.1: Get Sub-list

3.2: Return Sub-list

4: Get Previous
4.1: Get Sub-list
4.2: Return Sub-list

5: Get Current
5.1: Get Current
5.2: Return Value Object

6: Get Size
6.1: Get Size
6.2: 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
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
1: Create
ValueListiterator

2: Execute Search (index, count)


2.1: Execute Search (index, count) ValueList
2.1.1: Create

Return Sub List Return sub List

2: Execute Search (index+count, count) 2.1: Execute Search (index+count, count)


2.1.1: 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 onent Determine which EJBs
WebComp
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™
Session EJB tips
Push your development 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
Service Tier DON'Tfurther s Tech
Days

 DO NOT store large amount of data


in Stateful SessionEJB
 DO NOT access of Entity EJBs remotely
 DO NOT implement fine-grained
components as remote EJBs

52
Sun™
Push your development
Design Patterns further
Summary Tech
Days

Mediate business Locate services


processing
Locate services
Session Facade Service Locator

Obtain composite Encapsulate


value objects Access business list
data

Value Object Assembler Value List handler

Invoke
business Transactional Encapsulate
methods Data data
Business Components
Encapsu- Access data
Entity late data Transfer Object sources

Access data Encapsulate


sources data

Message Driven Data Access Object


Bean

53
Sun™
Push your development
Design Patterns further
Summary Tech
Days

 Data Transfer Object


 Exchanges data J2EE tiers

 Service Locator
 Holds results of JNDI lookups

 Value List Handler


 Handles larger result sets from database queries

 Business Delegate
 Simplifies the coupling between the J2EE Web &
EJB tiers
 Session Facade
 Provide business logic functionality

 Data Access Object


 Isolation layer for interfaces to a systems
resources
 Etc.
 www.sun.com/developer/blueprints/
54
Sun™
Push your development further Tech
Days

Persistence
Best
Practices
55
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
 JDBC RowSets (disconnected J2SE 1.5)
 Non-relational, non-object data access
 Use J2EE Connectors
56
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

57
Sun™
Push your of
Effect development
Good further
CMP Optimizations Tech
Days

28
24
20
16
12 Simple BMP
8 Optimized BMP
CMP
4
0
Benchmark # of Database
Score Calls

58
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.

59
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);

60
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

61
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>

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

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

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

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

for Container
 Optimization is possible in query
operation
 Because Query is defined in deployment
descriptor via EJB QL
 Optimization is possible because
persistent fields are only accessible
via get and set methods
 Lazy loading,Dirty writes,Optimistic locking

65
Sun™
Push
CMP yourOptimizations
development further Tech
Days

 Aggressive Loading
 Loading fields relationships and fields of
children 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

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

Vendor Specific Features


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

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

 Choose the lowest cost 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
68
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

69
Sun™
Push
EJB your development further
Summary 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.

 Use EJB 2.0 local interfaces for performance


improvements
 When running in same JVM.

70
Sun™
Push your development further Tech
Days

J2EE
Performance
Tips
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

 # Execute threads that requests run on


 JDBC
 connection pools
 Prepared statement cache size
 JVM Heap size
 (go to Performance code camp)
 EJB Bean Cache and Pools
 Correct settings depend on application,
test to determine sizes
73
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

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

 Stateful session bean and entity bean


cache
 Cache = EJB instances with state
 Session timeouts

 Stateless session and entity bean pools


 Pool = EJB instances with no assigned state

75
Sun™
Push your development
Entity Bean further Tech
Days

Bean pool size EjbActivate()

Bean cache size Does


not exist
NewInstance()
setEntityContext() unsetEntityContext()

pooled
ejbFind()
EJB
Instance
ejbCreate() ejbRemove()
ejbPostCreate()
ejbActivate() ejbPassivate()

ready

EJB EJB ejbStore()


ejbLoad()
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: do profiling with your application on
your app server
77
Sun™
Push your development
Stateful Session further
Bean Tech
Days

Bean cache size


Session time out
does not
exist

1) newInstance() ejbRemove()

2) setSessioncontext()

3)ejbCreate() ejbPassivate()

Method-ready

EJB EJB passive


Object Instance

business method EjbActivate()

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

and Message Driven Bean

Bean pool size


does not
exist

1) newInstance()

2) setSessioncontext() EjbRemove()

3)ejbCreate()

method-ready
pool
Business method
EJB
Instance

79
Sun™
The Sun's EJB Container
Push your development further 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 certified, high performance


type 2 (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 instead
of Statement when possible
 Tune statement caching

 Turn off Auto-Commit

83  Group updates into a transaction


Sun™
Push your development
Database further
Performance Tech
Days

 Common performance bottleneck


 Typical problems:
 Use small primary keys (number)
 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

84
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)

85
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]

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

Significantly Help Performance

 Session Facade
 Service Locator
 Value List Handler
 Data Transfer Object

87
Sun™
Push your development further Tech
Days

Some JMS

Messaging,

J2EE Best

Practices

88
Sun™
Push your development further
Point-to-Point Tech
Days

Example: Order and Fulfillment

Queue

JMS JMS

Java™ Pet
Store

89
Sun™
Push your development
Publish further
and Subscribe Tech
Days

Example: Stock Price Changes

Topic

Price Change

Traders/Brokers

90
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
Msg-
Desti MDB
Consume MDB
Queue Consumer driven
Instances
Instances
n- r
Bean
ation
Msg-Driven
Bean Class

91
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
92
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

93
Sun™
Push your development further Tech
Days

Tools
Summary
Resources
94
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

95
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

 JavaTM BluePrints Program


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

96
Sun™
Push your development further
Resources: Tech
Days

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

97 J2EE Performance Testing


Sun™
Push your development further Tech
Days

Sridhar Reddy
Technology Evangelist
sridhar.reddy@sun.com

Sun™ Tech Days

98

You might also like