J2EEBestPractices webinar
description
Transcript of J2EEBestPractices webinar
Push your development furtherSun™TechDays
1
J2EE Best Practices using a Real-life Example.Carol McDonaldTechnology [email protected]
Sun™ Tech Days
Push your development furtherSun™TechDays
2
eBay Architecture: How to Go…
Microsoft IIS
eBayISAPI.dll
MSXML
… to here?From there…J2EE™ Container
Web ContainerPresentation Tier
EJB™ Container
Business Tier
Integration Tier
Services
Con
figur
atio
n
Logg
ing
Secu
rity
Monolithic Proprietary
Layered Loosely coupled Modular Standards based
Push your development furtherSun™TechDays
3
What Is Needed…
Learning the technology is not enough
Industry best practices Proven solutions How to avoid bad practices?
Push your development furtherSun™TechDays
4
Core J2EE™ Patterns
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
Push your development furtherSun™TechDays
5
JavaTM BluePrints Program
http://java.sun.com/blueprints JavaTM Technology Series
books– Designing Enterprise Applications
with the J2EE Platform, 2nd Edition● Covers J2EETM 1.3 platform features
– 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
Push your development furtherSun™TechDays
6
Agenda
Web Tier best practices EJB Tier best practices Persistence Options Container Managed Persistence
J2EE Performance JMS Best Practices (depending on the time)
Push your development furtherSun™TechDays
7
Some Web TierBest Practicesand Patterns
Push your development furtherSun™TechDays
8
Layering
EJB Session Beans
Web Tier or Client
Data Transfer Objectsi.e. Business Data Values
Business Logic LayerService Layer
Domain LayerPersistent Entities
Presentation Layer
Network
EntityEJBs
Push your development furtherSun™TechDays
9
Rationale for Layers
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
Push your development furtherSun™TechDays
10
Model View Controller
Client
Problem Domain Services
Enterprise Resources
Controller View
Persistence Layer
Model Layer
Presentation Layer
Thin Browser
HTTP Request HTML Page
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
Push your development furtherSun™TechDays
11
Model View Controller
ModelView
Controller
Client Web EJB Tier
Request
ForwardEvent
Data
Response
ServletServlet
JSPJSP BeanBean
BusinessEvent
MVC Pattern
Model
✗Separate:●Model data●Control●Presentation of view
Push your development furtherSun™TechDays
12
Service to Worker
CommandFactory
Front Controller
Dispatcher
CommandHelper
1. Request
3. Parse Request
2. Common logic
5. Create
6. Execute
8. Dispatch7. Business logic
4. Get cmd
ViewHelperDataBean
View
Client
Servlet
JSPJava™ Objects
10. Response
9. Get Data
= MVC Pattern with more detail
Push your development furtherSun™TechDays
13
Use an MVC Framework
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
Push your development furtherSun™TechDays
14
Struts MVC Framework
Model
Action
Action
Action
Action
ActionServlet(Controller)
View 1
View 2
Struts-config.xml........................
1 23
4
5
Form Bean
Push your development furtherSun™TechDays
15
Struts and Core J2EE Patterns
Client
Action Servlet Action
ActionForward
ActionFormJSP View
Front Controller Model
View HelperView
Action Mapping
(xml)
BusinessService
Command
Dispatcher
Response
Request
Uses
Push your development furtherSun™TechDays
16
Ebay.com: Presentation Tier
Request
Response
Client
BusinessServiceCommand
Request Handler
InterceptingFilter
Front Controller
Navigator Dispatcher
Navigation and Dispatch
View Processor
TransformerHelper
InterceptingFilter
ViewProcessor
XML
XSL Core J2EE
Pattern
Strategy
?
Push your development furtherSun™TechDays
17
Business Delegate
Client independent from ejb tier
Ejb details hidden
Mock objects can be used to test client w/o ejb tier
Push your development furtherSun™TechDays
18
Ebay.com: Presentation Tier
Request
Response
Client
BusinessServiceCommand
Request Handler
InterceptingFilter
Front Controller
Navigator Dispatcher
Navigation and Dispatch
View Processor
TransformerHelper
InterceptingFilter
ViewProcessor
Business Delegate
Service Locator
XML
XSL Core J2EE
Pattern
Strategy
Service Interface
Push your development furtherSun™TechDays
19
Cache for Performance
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
Push your development furtherSun™TechDays
20
Service Locator Pattern
Use the Service Locator Pattern toCache references obtained by JNDI lookups (ejb references, datasources, jms connection)
Repeated lookups can be expensive!
DON'T DO
EJBClient
EJBClient
JMSClient
JDBCClient
EJBClient
EJBClient
ServiceLocator
JMSClient
JDBCClient
JNDI
JNDI
Push your development furtherSun™TechDays
21
ServiceLocator code 01 public class ServiceLocator {02 private InitialContext ic;03 private Map cache;04 private static ServiceLocator me;0506 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 }
Push your development furtherSun™TechDays
22
ServiceLocator code 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
Push your development furtherSun™TechDays
23
Client code 01 ServiceLocator serviceLocator = 02 ServiceLocator.getInstance(); 03 try { 04 ProjectHome projectHome =(ProjectHome) 05 serviceLocator.getHome(“ProjectHome.class”); . . .
Push your development furtherSun™TechDays
24
Tips for Servlet Performance
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()
Push your development furtherSun™TechDays
25
Servlet Tips
DO use high performance J2EE design patterns MVC, Service Locator
DON’T hold resources – explicitly free them
Push your development furtherSun™TechDays
26
Tips for JSPs
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
Push your development furtherSun™TechDays
27
Some EJB Tier Best Practicesand Patterns
Push your development furtherSun™TechDays
28
Do you need EJBs? 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?
Push your development furtherSun™TechDays
29
Architecting Applications
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
ebay Case Study
Push your development furtherSun™TechDays
30
ebay Use case realization
View Items
Any User
View Itemsby category
Any user can view auction items by category
ebay Case Study
Push your development furtherSun™TechDays
31
AssembleData
Use caseBiz logic
Convert to Biz Command
CentralizeRequest Hndlg
View Items Design Requirements
Retrieve Data by category
ebay Case Study
Push your development furtherSun™TechDays
32
Action Command
Front Controller
SessionFacade
BusinessDelegate
View Items Design
ServiceLocator
TransferObject
AssemblerTransferObject
Value ListHandler
Data AccessObject
ebay Case Study
Push your development furtherSun™TechDays
33
WEB Tier
Presentation Business Logic &Messaging Fabric
Data Integration& Persistence
Core Application Design Patterns
FRONTCONTROLLER VIEW
COMMANDobject
Request Response
MODEL
DATATRANSFER
OBJECT
BUSINESSSERVICEFACADE
Value List HandlerDATA
ACCESSOBJECT
DATATRANSFER
OBJECT
SessionEJB
Servlet
JSP
Java™ Objects
Session EJB
Ebay Case Study
Push your development furtherSun™TechDays
34
Data Transfer Object
DON'T DOtoo much network traffic
DOReduce network trafficwith Data Transfer Object
ClientObject EJB
Before
ClientObject
EJBItem InfoData Transfer Object
After
GetItemInfo()
GetCity()
GetState()
GetZipCode()
GetCity()
GetState()
GetZipCode()
Networkboundary
Networkboundary
Return DTO
A Data Transfer Object encapsulates a set of data values to return to the client in one network transfer
Push your development furtherSun™TechDays
35
WEB Tier
Presentation Business Logic &Messaging Fabric
Data Integration& Persistence
Core Application Design Patterns
FRONTCONTROLLER VIEW
COMMANDobject
Request Response
MODEL
DATATRANSFER
OBJECT
BUSINESSSERVICEFACADE
Value List HandlerDATA
ACCESSOBJECT
DATATRANSFER
OBJECT
SessionEJB
Servlet
JSP
Java™ Objects
Session EJB
Push your development furtherSun™TechDays
36
Data Access Object
BusinessObject DataAccessObject DataSource
TransferObject
Uses Encapsulates
creates/uses
obtains/modifies
Use Data Access Objects to encapsulate data-access logic
-provides a simplified interface for performing complex JDBC operations
-allows decoupling of data-access optimizations
Use DAO for read-only tabular access to a large set of data, when query results are large and short-lived
Push your development furtherSun™TechDays
37
EJB Tier patternsData 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()); } } …. }
Push your development furtherSun™TechDays
38
WEB Tier
Presentation Business Logic &Messaging Fabric
Data Integration& Persistence
Core Application Design Patterns
FRONTCONTROLLER VIEW
COMMANDobject
Request Response
MODEL
DATATRANSFER
OBJECT
BUSINESSSERVICEFACADE
Value List HandlerDATA
ACCESSOBJECT
DATATRANSFER
OBJECT
SessionEJB
Servlet
JSP
Java™ Objects
Session EJB
Push your development furtherSun™TechDays
39
Value List Handler For querying, filtering, and
displaying large amounts of data: Value List Handler handles
the search, can cache results and provides a traversable result set
Client ValueListHandler<<List>>
ValueList TransferObject
DataAccessObject
InterfaceValueListIterator
+GetSize():int+getCurrentElement():Object+getPreviousElements(count:int):List+getNextElements(count:int):List+resetIndex():void
Push your development furtherSun™TechDays
40
Example Caching Results
Create
Execute Search
Get Next
Get Previous
Get Current
Get Size
Return Sub-list
Return Sub-list
Return Value Object
Return Size
Execute Search
Return Value List
Get Sub-list
Get Sub-list
Get Current
Get Size
Create
Client
ValueListHandler
DataAccessObject
ValueListValueListiterator
Return Sub List
Stateful Session
Push your development furtherSun™TechDays
41
Returning Search Results Options
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)
Push your development furtherSun™TechDays
42
Stateless Example
Create
Execute Search (index, count) Execute Search (index, count)
Return sub List
Create
Client
ValueListHandler
DataAccessObject
ValueList
ValueListiterator
Return Sub List
Execute Search (index+count, count) Execute Search (index+count, count)
Return sub List
Create
Return Sub List
Stateless Session
Select * FROM item WHERE id=? LIMIT [count]OFFSET [startIndex]
Push your development furtherSun™TechDays
43
WEB Tier
Presentation Business Logic &Messaging Fabric
Data Integration& Persistence
Core Application Design Patterns
FRONTCONTROLLER VIEW
COMMANDobject
Request Response
MODEL
DATATRANSFER
OBJECT
BUSINESSSERVICEFACADE
Value List HandlerDATA
ACCESSOBJECT
DATATRANSFER
OBJECT
SessionEJB
Servlet
JSP
Java™ Objects
Session EJB
Push your development furtherSun™TechDays
44
Session Facade pattern Entity Bean 1
Entity Bean 2
Java™ Object
Data Access Object 2
Data Access Object 1
1. doThis(...)
2. getData()
3. process
2. getData()
Session BeanEntity BeanPlain Java™ Object
Use the Session Facade: 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
Session Facade
Client
Session Bean
Push your development furtherSun™TechDays
45
Direct Entity Bean access results in excessive network overheadand multiple transactions
Don’t: EJB
Network
Client
Direct Bean Access
Do:EJBNetwork
ClientFacade
Use the Session Facade pattern
Direct Entity Bean access results in excessive network overhead
To Execute complex use cases in a single network call to reduce network overhead
Push your development furtherSun™TechDays
46
EJBclient
EJBObject
Network
Local vs. Remote Interfaces
Pass by Value:Serialize/deserialize method parameters
Pass by Reference:Better performance
Remote Interfaces Local Interfaces
EJBclient
EJBObject
Use the Session Facade To group finer grained calls to local entity beans
Push your development furtherSun™TechDays
47
Design your local & remote EJBs
AdminRemoteFacade
LineItem
Purchase Order
Address
CreditCard
RelationshipReference
JavaClient
RemoteFacade
WebComponent
WebComponent
WebComponent
BusinessDelegate
Determine which EJBswill be collocated within sameVM
Use Session Facade to group finer grained calls to local EJBs in a Coarse Grained Interface
Push your development furtherSun™TechDays
48
Use the Session Facade
Check contextx to see if updates will work
Application Server
Transaction Manager Transaction
context
DataBase Serveror JMS Provider
ResourceClient FacadeInventory
Order
Check OutTX_REQUIRED TX_REQUIRED
Create context x
Update Inventory
Add to context x
createOrder
Add to context x
Commitor rollbackStart Prepare
To group related updates into container managed transactions
Push your development furtherSun™TechDays
49
eBay.com: Business Tier
DataSource
Dispatch
ApplicationController
BusinessLogic/Data
TransferObject
DAO
ApplicationServiceFacade
Persistence
ContextObject
TransferObject
Assembler
BusinessObject
ValueList
Handler
Domain Store
Core J2EE
Pattern
Strategy
Command
ebay Case Study
Push your development furtherSun™TechDays
50
Session EJB tips
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
Push your development furtherSun™TechDays
51
Stateless or Stateful Session EJB?
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
Push your development furtherSun™TechDays
52
PersistenceBest
Practices
Push your development furtherSun™TechDays
53
Data Access Options in J2EE:
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
Push your development furtherSun™TechDays
54
BMP vs. CMP
CMP Bean
EJB Container
BMPBean
EJB Container
JDBCDriver
JDBCSQLJ
SQL
JDBCDriver
SQL
PersistenceManager
BeanState
Database
BeanState
Database
JDBCSQLJ
1) Bean provider manages State and Data consistency2) Bean provider handles relationships and OR Mapping
1) Container manages State and Data consistency2) Container/PM provides concurrency, relationships and OR Mapping
Push your development furtherSun™TechDays
55
CMP 2.0 Entity Beans
<<interface>>java.io.Serializable
CMP Entity Bean subclass(Contains persistence logic)
CMP Entity Bean abstract class(Contains data handling logic)
<<interface>>javax.ejb.EntityBean
<<interface>>javax.ejb.EnterpriseBean
You (bean provider) write this code.
Container provides this class.
Entity Bean is now an abstract class, container extends it
Push your development furtherSun™TechDays
56
Container Managed Relationships
1
1
1
M M
1
Local Entity
Local Entity
OrderBean Product
Address
Shipping Address
LineItems ProductOrdered
Client
Order
OrderHome LineItem
EJB TierLocal Entity
Push your development furtherSun™TechDays
57
Accessors for CMP and CMR
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);
Push your development furtherSun™TechDays
58
CMP 2.0 Relationship Handling
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>
Push your development furtherSun™TechDays
59
Example CMP Wizard
Push your development furtherSun™TechDays
60
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
Advantages of CMP 2.0 for developer
Push your development furtherSun™TechDays
61
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
Advantages of CMP 2.0 for Container
Push your development furtherSun™TechDays
62
Some CMP Optimizations
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
Push your development furtherSun™TechDays
63
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
CMP: Standard Vs. Vendor Specific Features
Push your development furtherSun™TechDays
64
Pessimistic Locking
Time State inDatabase
Begin TxnBegin TxnBegin TxnBegin Txnread initialread initialread initialread initial balance w/Lock balance w/Lock balance w/Lock balance w/Lock........balance += 1000balance += 1000balance += 1000balance += 1000 ........CommitCommitCommitCommit
1000
20002000
Begin TxnBegin TxnBegin TxnBegin Txnread initial read initial read initial read initial balance w/lockbalance w/lockbalance w/lockbalance w/lock
(blocks ..)(blocks ..)(blocks ..)(blocks ..)
unblocksunblocksunblocksunblocks
balance += balance += balance += balance += 1000100010001000
CommitCommitCommitCommit
2000
3000 3000
C2C1
The entity blocks until previous transaction commits
1000
Serialized Access to same Bean
Push your development furtherSun™TechDays
65
Retry
3000
2000
Concurrent Access to same Bean (same Primary Key)Lock obtained at update time, conflict detection
Optimistic Locking With “ Update-conflict” Detection
Time State inDatabase
Begin TxBegin TxBegin TxBegin TxSelect initialSelect initialSelect initialSelect initial balance balance balance balance
........balance += 1000balance += 1000balance += 1000balance += 1000updateupdateupdateupdate........CommitCommitCommitCommit
1000
20002000
Begin TxBegin TxBegin TxBegin TxSelect initial Select initial Select initial Select initial balancebalancebalancebalance........
balance += 1000balance += 1000balance += 1000balance += 1000
updateupdateupdateupdate Exception Exception Exception Exception
........CommitCommitCommitCommit3000
C2C1
10001000
Concurrent Access to same Bean
Push your development furtherSun™TechDays
66
Usage Guidelines
Pessimistic Recommended for
consistency when concurrent updates would be frequent
Optimistic Use when
concurrent access is mostly reading
For scalability Requires
exception handlingSunOne deployment descriptor
<consistency><lock-when-loaded/>
</consistency>
Push your development furtherSun™TechDays
67
Chose optimistic concurrency forCMPs with “read-mostly” access
Tradeoff between performanceand consistency in transactions
Consistency Levels in CMP
Push your development furtherSun™TechDays
68
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
Consistency Levels in CMP
Push your development furtherSun™TechDays
69
Database Isolation Modes
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
Push your development furtherSun™TechDays
70
Entity Bean Tips
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
Push your development furtherSun™TechDays
71
J2EE Performance Tips:
how to get the mostout of your Application
Server
Push your development furtherSun™TechDays
72
Application Resources
Standard application resources: CPU Memory I/O Network Database
Push your development furtherSun™TechDays
73
Tune App Server
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
Push your development furtherSun™TechDays
74
Tune Key Container Parameters
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
Push your development furtherSun™TechDays
75
The EJB Container
PoolingPoolingPoolingPooling CachingCachingCachingCaching
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
Allow for reuse of bean instances
Pooling and Caching of EJB Instances
Push your development furtherSun™TechDays
76
Entity Bean
Does not exist
pooled
ready
NewInstance()setEntityContext() unsetEntityContext()
ejbCreate()ejbPostCreate()
ejbRemove()
business method
ejbStore()ejbLoad()
ejbFind()
ejbActivate() ejbPassivate()
EjbActivate()
EJBInstance
EJBObject
EJBInstance
Bean pool sizeminimizes creation and initialization
Bean cache sizeminimizes activation and passivation
Push your development furtherSun™TechDays
77
Entity Bean Caching
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 application on your app server
Push your development furtherSun™TechDays
78
Stateful Session Bean
Method-ready
ejbRemove()
business method
does not exist
1) newInstance()
2) setSessioncontext()
3)ejbCreate() ejbPassivate()
EjbActivate()
passiveEJBInstance
EJBObject
removal time out
Bean cache sizeminimizes activation and passivation
Push your development furtherSun™TechDays
79
Stateless Session Bean and Message Driven Bean
EJBInstance
method-ready pool
EjbRemove()
Business method
does not exist
1) newInstance()
2) setSessioncontext()
3)ejbCreate()
Bean pool sizeminimizes creation and initialization
Push your development furtherSun™TechDays
80
The Sun's EJB Container
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 usagepattern (reads, updates, creates, removes ...)
Cache Tunables
Push your development furtherSun™TechDays
81
The Sun's EJB Container
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
Pool Tunables
Push your development furtherSun™TechDays
82
The Sun's EJB Container
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>
Configuring Pool and Cache
Push your development furtherSun™TechDays
83
JDBC Tips
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
Push your development furtherSun™TechDays
84
Database Statement Caching
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>
Push your development furtherSun™TechDays
85
Database Performance
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
Push your development furtherSun™TechDays
86
Performance Tips Summary
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)
Push your development furtherSun™TechDays
87
EJB Tips Summary
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.
Push your development furtherSun™TechDays
88
Manage Expensive Resources
Cache “EJB homes” Cache data sources Minimize use of HTTP sessions Release database connections Remove unused stateful session beans Use local Interfaces [Session Facade]
Push your development furtherSun™TechDays
89
Session Facade Service Locator Value List Handler Data Transfer Object
Design Patterns can Significantly Help Performance
Push your development furtherSun™TechDays
90
Some JMS Messaging, J2EE BestPractices
Push your development furtherSun™TechDays
91
JMS Communication
Consumer
JMS Provider
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
Producer Destination
Push your development furtherSun™TechDays
92
Use JMS for
Asynchronous Interaction Concurrent processing Scalability Batch processing
Broadcasting messages to multiple recipients
Reliable messaging Messaging with Transaction Support Loose Coupling
Push your development furtherSun™TechDays
93
Message-Driven Bean
Container
Destin-
ation
Consumer
Msg-drivenBeanInstances
High Scalability, High Throughput MDB instances are pooled by the container Allow for asynchronous concurrent message consumption
from the same destination
JMS Provider
Container
QueueMDB
ConsumerMDB
Instances
Msg-DrivenBean Class
Concurrent Asynchronous Processing
Push your development furtherSun™TechDays
94
EJB Tier
Address Entity
OrderApproval
MDB
LineItem Entity
Mailer MDB
CardEntity
AsynchronousMessageDelivery
Purchase Order Entity
1:m
MDB Facade Pattern
Use the MDB Facade: provide a simple asynchronous interface to a complex
subsystem of enterprise beans
Push your development furtherSun™TechDays
95
JMS
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
Push your development furtherSun™TechDays
96
XML Message Facade
EJB Architectural Pattern
ExternalApplication
JMSQueues
MessageDrivenBean
StatelessSession
EJB
EntityBean
XML Messaging Facade
Asynchronous Synchronous
Example implementation of XML interaction modelon top of Java™ interaction model
EntityBean
EntityBean
XMLmsg
Java™Value
Objects
Ref JavaOne
Push your development furtherSun™TechDays
97
Tips for XML messaging
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
Push your development furtherSun™TechDays
98
Asynchronous Web Services
RDBMSEAI ResourceAdapters
LegacySystems
Data Base
ERP
Business Services
Webcontainer
DomainObjects
EntityEJBMDB DAO
Connector
MDB
Soap
Message Services
EntityEJBMDB
SessionEJB
SessionEJB
BusinessDocument
Webcomponent
Push your development furtherSun™TechDays
99
FUTURE: JBI and J2EE
208 “Binding” SPI
208 “Machine” SPI
Binding Framework
WS-I EDI VAN
SOAP EIS resource AS1/AS2
EJB Module(EJB API)
JBI BP Module (WS-BPEL and WSDL APIs)
Normalized Message “Bus”
Web App. Module(JSP/ServletAPI)
JMS
MQ
JCA
Push your development furtherSun™TechDays
100
ToolsSummary
Resources
Push your development furtherSun™TechDays
101
Use Tools
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
Push your development furtherSun™TechDays
102
Summary
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
Push your development furtherSun™TechDays
103
Resources:
http://java.sun.com/blueprints
J2EE Performance Testing
Java Performance Tuning
Push your development furtherSun™TechDays
104
Carol McDonaldTechnology [email protected]
Sun™ Tech Days