Push your development furtherusing J2EE Best Practices Real-life Examples. Sridhar Reddy Technology Evangelist [email protected]

Sun™ Tech Days

1

Sun™ Tech Days

Push yourIs development further What Needed…

Sun™ Tech Days

 Learning the technology is

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

2

Push yourArchitecture: development further How eBay

From there…

to Go…

… to here?

Microsoft IIS

J2EE™ Container

EJB™ Container Business Tier

MSXML

Integration Tier



Monolithic Proprietary

   

3

Layered Loosely coupled Modular Standards based

Security

eBayISAPI.dll

Logging

Presentation Tier

Services Configuration

Web Container



Sun™ Tech Days

™ development further

Push yourJ2EE Core

Patterns

Sun™ 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

Push your BluePrints development further Java Program TM

 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™ Tech Days

Push your development further Agenda

Sun™ 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

Push your development further

Sun™ Tech Days

Some Web Tier Best Practices and Patterns 7

Sun™ Tech Days

Push your development further Layering

Web Tier or Client

Network

Data Transfer Objects i.e. Business Data Values

EJB Session Beans

Business Logic Layer Service Layer

Entity EJBs

8

Presentation Layer

Domain Layer Persistent Entities

Push your development further Rationale for Layers

Sun™ 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™ Tech Days

Push your development further Model View Controller

 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 Client

Thin Browser HTTP Request

Presentation Layer

Model Layer

Persistence Layer

10

Controller

HTML Page

View

Problem Domain Services

Enterprise Resources

Sun™ Tech Days

Push your development further Model View Controller

Separate: Model data Control Presentation of view 

Request

Response

Servlet

Controller

Business Event

Forward Event

Bean

JSP

View Client

Data

Web MVC Pattern

11

Model

Model EJB Tier

Sun™ Tech Days

Push your development further Service to Worker

Command Factory

3. Parse Request 5. Create 1. Request Client

Front Controller

2. Common logic

4. Get cmd

6. Execute

Command Helper

8. Dispatch 10. Response

7. Business logic

View Dispatcher

Servlet JSP Java™ Objects

12

9. Get Data

View Helper Data Bean

Push further Useyour andevelopment MVC Framework

Sun™ Tech Days

 Faster, easier development of  Request processing  Response generation

 Use Struts, JSF, Sun ONE ... application framework

13

Sun™ Tech Days

Push your development further Struts Framework

Form Bean

View 1

1

Action

2 4 ActionServlet (Controller)

Action Model

5

Action View 2 Struts-config.xml ........ ........ ........

14

3

Action

Push your development further Struts and Core J2EE Front Controller

Request Action Servlet

Action Mapping (xml)

Patterns Command

Action

Client Uses Response

JSP View

View 15

Action Forward

Dispatcher

Action Form

View Helper

Sun™ Tech Days

Model

Business Service

Push your development further Ebay.com: Presentation

Sun™ Tech Days

Tier

Request Handler

Request Intercepting Filter

Front Controller

Navigation

Command

?

Business Service

and Dispatch

Client Navigator

Dispatcher

XML

View Processor Intercepting Filter

Response

View Processor

Transformer Helper

XSL

Core J2EE Pattern Strategy

16

Push your development further

Business Delegate  Client

independent from ejb tier  Ejb details

hidden  Mock objects can

be used to test client w/o ejb tier

17

Sun™ Tech Days

Push your development further Ebay.com: Presentation

Sun™ Tech Days

Tier

Request Handler

Service Interface

Request Intercepting Filter

Front Controller

Navigation

Command

Service Locator

Dispatcher

XML

View Processor Intercepting Filter

Response

Business Service

and Dispatch

Client Navigator

Business Delegate

View Processor

Transformer Helper

XSL

Core J2EE Pattern Strategy

18

Push your development further Cache for Performance

Sun™ 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™ Tech Days

Push your development further Service Locator Pattern

DON'T EJB Client

EJB Client

DO JMS Client

JNDI

JDBC Client

EJB Client

JMS Client Service Locator JDBC Client

EJB 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

Push your development further ServiceLocator code

Sun™ 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

Push your development further ServiceLocator code

Sun™ Tech Days

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

03 04 05 06 07 08 09 10 11 12 15

22

EJBHome home = null; if (cache.containsKey(jndiHomeName)) { home = (EJBHome) cache.get(jndiHomeName); } else { Object objref = ic.lookup(jndiHomeName); Object obj = PortableRemoteObject.narrow(objref, className); home = (EJBHome)obj; cache.put(jndiHomeName, home); } return home; }

Push your development further Client code

01 ServiceLocator serviceLocator = 02

ServiceLocator.getInstance();

03 try { 04 05

...

23

ProjectHome projectHome =(ProjectHome) serviceLocator.getHome(“ProjectHome.class”);

Sun™ Tech Days

Push development further Tipsyour for Servlets

Sun™ 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

Push your development Servlet Tips further

Sun™ Tech Days

 DO use high performance J2EE

design patterns  MVC, Service Locator

 DON’T hold resources – explicitly

free them

25

Push development Tipsyour for JSPs further

Sun™ Tech Days

 Avoid scriptlets in JSP  Use JSTL (JSP 2.0 Standard Tag Libraries): 

 Pass data to JSP in Servlet request object not

session  If JSP does not use the HTTP session  Use to prevent

HTTP Sessions from being automatically created

26

Push your development further

Sun™ Tech Days

Some EJB Tier Best Practices and Patterns 27

Push development further Do your you need EJBs?

Sun™ 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

Push your development further Architecting Applications

Sun™ 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™ Tech Days

Push yourUse development ebay case further realization

ebay Case Study

View Items by category Any User

Any user can view auction items by category

30

View Items

Push yourItems development further Requirements View Design

Sun™ Tech Days

ebay Case Study Centralize Request Hndlg

Convert to Biz Command Assemble Data Use case Biz logic Retrieve Data by category

31

Sun™ Tech Days

Push yourItems development further View Design

ebay Case Study Front Controller

Transfer Object Assembler

Action Command

Business Delegate

Service Locator

32

Session Facade

Value List Handler

Data Access Object

Transfer Object

Push yourApplication development further Core Design Patterns

Ebay Case Study Presentation

Response

Request

FRONT CONTROLLER

Data Integration & Persistence

BUSINESS SERVICE FACADE

VIEW

MODEL

COMMAND object

DATA TRANSFER OBJECT

WEB Tier

33

Business Logic & Messaging Fabric

Sun™ Tech Days

Servlet

Java™ Objects

JSP

Session EJB

Value List Handler

DATA TRANSFER OBJECT

SessionEJB

DATA ACCESS OBJECT

Sun™ Tech Days

Push yourTransfer developmentObject further Data Client Object

EJB Network boundary

GetCity() GetState()

Before

DON'T DO too much network traffic

GetZipCode()

Client Object

Item Info Data Transfer Object

EJB

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 clie nt in one ne twork tra ns fe r

GetItemInfo() Return DTO GetCity()

After

DO Reduce network traffic with Data Transfer Object

GetState() GetZipCode() Network boundary

34

Push yourApplication development further Core Design Patterns Business Logic & Messaging Fabric

Presentation

Response

Request

FRONT CONTROLLER

Data Integration & Persistence

BUSINESS SERVICE FACADE

VIEW

MODEL

COMMAND object

DATA TRANSFER OBJECT

WEB Tier

35

Sun™ Tech Days

Servlet

Java™ Objects

JSP

Session EJB

Value List Handler

DATA TRANSFER OBJECT

SessionEJB

DATA ACCESS OBJECT

Sun™ Tech Days

Push yourAccess development further Data Object Use DAO for read-only tabular access to a large set of data, when query results are large and short-lived BusinessObject

Uses

DataAccessObject

creates/uses

obtains/modifies

36

Encapsulates

DataSource

Use Data Access Objects to encapsulate data-access logic -provides a simplified interface for performing complex JDBC operations -allows decoupling of data-access optimizations

TransferObject

Push your development further EJB Tier patterns

Sun™ 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

DAOs as the app is designed for different databases The name of the particulary DAO class is lookup in the env. settings given in the deployment descriptor Reflection is used to instantiate a concrete instance of the class

Example: EbayDAOFactory

Push yourApplication development further Core Design Patterns Business Logic & Messaging Fabric

Presentation

Response

Request

FRONT CONTROLLER

Data Integration & Persistence

BUSINESS SERVICE FACADE

VIEW

MODEL

COMMAND object

DATA TRANSFER OBJECT

WEB Tier

38

Sun™ Tech Days

Servlet

Java™ Objects

JSP

Session EJB

Value List Handler

DATA TRANSFER OBJECT

SessionEJB

DATA ACCESS OBJECT

Sun™ Tech Days

Push your development further Value List Handler

 For querying, filtering, and

Interface

ValueListIterator

+GetSize():int +getCurrentElement():Object +getPreviousElements(count:int):List +getNextElements(count:int):List +resetIndex():void

displaying large amounts of data: 

Value List Handler handles the search, can cache results and provides a traversable result set

Client

ValueListHandler

ValueList

DataAccessObject

39

TransferObject

Sun™ Tech Days

Push your development furtherResults Example Caching Stateful Session

Client

ValueListHandler

1: Create

ValueListiterator

2: Execute Search

DataAccessObject

ValueList

2.1: Execute Search 2.1.1: Create

Return Sub List

3: Get Next

Return Value List

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

Push your development further Returning Search Results Options

Sun™ 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=? [count] OFFSET [startIndex]

LIMIT

 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™ Tech Days

Push your development further Stateless Example Stateless Session

Client

1: Create

ValueListHandler ValueListiterator

2: Execute Search (index, count)

Return Sub List

2: Execute Search (index+count, count)

Return Sub List

DataAccessObject

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

Return sub List

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

Return sub List

Select * FROM item WHERE id=? LIMIT [count]OFFSET [startIndex]

42

ValueList

Push yourApplication development further Core Design Patterns Business Logic & Messaging Fabric

Presentation

Response

Request

FRONT CONTROLLER

Data Integration & Persistence

BUSINESS SERVICE FACADE

VIEW

MODEL

COMMAND object

DATA TRANSFER OBJECT

WEB Tier

43

Sun™ Tech Days

Servlet

Java™ Objects

JSP

Session EJB

Value List Handler

DATA TRANSFER OBJECT

SessionEJB

DATA ACCESS OBJECT

Sun™ Tech Days

Push your development further Session Facade pattern Session Bean

Entity Bean 1

Entity Bean Plain Java™ Object

Client 1. doThis(...)

2. getData()

2. getData() Entity Bean 2

Data Access Object 1

Session Bean

Data Access Object 2

Session Facade

3. process

 Use the Session Facade:

Java™ 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

Push development further Useyour the Session Facade

Sun™ Tech Days

pattern

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: Network Client

45

F a c a d e

EJB

Direct Entity Bean access results in excessive network overhead

Sun™ Tech Days

Push yourthe development furtherFacade Use Session To group finer grained calls to local entity beans

Local vs. Remote Interfaces Remote Interfaces EJB client

EJB Object

Local Interfaces EJB client

EJB Object

Network Pass by Value: Serialize/deserialize method parameters

46

Pass by Reference: Better performance

Push your development further& Design your local

remote EJBs

Sun™ Tech Days

Use Session Facade to group finer grained calls to local EJBs in a Coarse Grained Interface Java Client Remote Facade

WebComp onent

WebComp onent

WebComp onent Business Delegate

Relationship Reference

Admin Remote Facade

Determine which EJBs will be collocated within same VM

LineItem CreditCard Purchase Order Address

47

Sun™ Tech Days

Push development further Useyour the Session Facade

To group related updates into container managed transactions Application Server TX_REQUIRED

Check Out

Client

Facade

TX_REQUIRED

DataBase Server or JMS Provider

Update Inventory Inventory

Order

Resource

createOrder Commit or Start Prepare rollback

Transaction Create context x Manager Add to context x

Transaction context

Add to context x Check context x to see if updates will work

48

Push your development further eBay.com: Business

Sun™ Tech Days

Tier

ebay Case Study Dispatch Application Controller

Command

Context Object

Persistence Domain Store

DAO

Data Source

Business Logic/Data Application Service Facade

Business Object

Transfer Object Assembler

Value List Handler

Transfer Object

Core J2EE Pattern Strategy

49

Session EJB tips

Push your development further

Sun™ 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

Push your development further Stateless or Stateful

Session EJB?

Sun™ 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

Push your development further Service Tier DON'T

s

Sun™ 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™ Tech Days

Push your development further Design Patterns Summary Mediate business processing Locate services

Session Facade Obtain composite value objects

Encapsulate data

Access data sources

Message Driven Bean

53

Access business list

Value List handler Encapsulate data

Transactional Data Business Components

Entity

Service Locator

Encapsulate data

Value Object Assembler Invoke business methods

Locate services

Transfer Object Encapsulate data

Data Access Object

Access data sources

Push your development further Design Patterns Summary

Sun™ 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

Push your development further

Persistence Best Practices 55

Sun™ Tech Days

Push yourAccess development further Data Options

in J2EE:

Sun™ 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™ Tech Days

Push yourvs. development BMP CMP further

BMP Bean

JDBC SQLJ

JDBC Driver

SQL

Bean State Database

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

CMP Bean EJB Container

JDBC SQLJ

Persistence Manager

JDBC Driver

SQL

Bean State Database

1) Container manages State and Data consistency 2) Container/PM provides concurrency, relationships and OR Mapping

57

Push your of development Effect Good further CMP Optimizations

Sun™ Tech Days

28 24 20 16 12

Simple BMP Optimized BMP CMP

8 4 0

Benchmark Score

58

# of Database Calls

Push your2.0 development CMP Entity further Beans

Sun™ Tech Days

Entity Bean is now an abstract class, container extends it java.io.Serializable

javax.ejb.EnterpriseBean

javax.ejb.EntityBean

59

CMP Entity Bean abstract class (Contains data handling logic)

You (bean provider) write this code.

CMP Entity Bean subclass (Contains persistence logic)

Container provides this class.

Push your development further and Accessors for CMP

CMR

Sun™ 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

Push your development further Container Managed

Sun™ Tech Days

Relationships

Address Order

1

Local Entity

Shipping Address Local Entity

1 Client

Product

OrderBean

1

1 LineItems

ProductOrdered

M OrderHome

LineItem Local Entity

EJB Tier 61

M

Push your2.0 development further CMP Relationship

Handling

Sun™ Tech Days

 In CMP 2.0, you declare fields and

relationships in deployment descriptor  Container generates all the necessary code ... define your enterprise beans ... elements represent container-managed persistent fields ... define EJB relationships ...

62

Push your development further Example CMP Wizard

63

Sun™ Tech Days

Push your development Advantages of further CMP 2.0 for developer

Sun™ Tech Days

 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

Push your development Advantages of further CMP 2.0 for Container

Sun™ Tech Days

 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

Push yourOptimizations development further CMP

Sun™ 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

Push yourStandard development further CMP: Vs. Vendor Specific Features

Sun™ Tech Days

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

Push your development further Modes Database Isolation

Sun™ 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

Push your development further Entity Bean Tips

Sun™ 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

Push your development further EJB Summary

Sun™ 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

Push your development further

J2EE Performance Tips 71

Sun™ Tech Days

Push your development further Application Resources

 Standard application resources:

72



CPU



Memory



I/O



Network



Database

Sun™ Tech Days

Push yourApp development further Tune Server

Sun™ 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™ Tech Days

Push your development further The EJB Container

Pooling and Caching of EJB Instances

Allow for reuse of bean instances Pooling

Caching

creation +

activation /

initialization

passivation

for message-driven

yes

no

for stateless session

yes

no

for stateful session

no

yes

for entity beans

yes

yes

objective: minimize

74

Push yourKey development further Tune Container

Parameters

Sun™ 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™ Tech Days

Push your development Entity Bean further Bean pool size Bean cache size

EjbActivate()

Does not exist NewInstance() setEntityContext()

unsetEntityContext()

pooled

ejbFind() EJB Instance

ejbCreate() ejbPostCreate()

ejbRemove() ejbActivate()

ejbPassivate()

ready

ejbLoad()

EJB Object

EJB Instance

business method

76

ejbStore()

Push your development further Entity Bean Caching

Sun™ 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™ Tech Days

Push your development further Stateful Session Bean Bean cache size Session time out does not exist

ejbRemove()

1) newInstance() 2) setSessioncontext() 3)ejbCreate()

ejbPassivate()

Method-ready EJB Object

business method

78

passive

EJB Instance

EjbActivate()

Push your development further Bean Stateless Session and Message Driven Bean

Sun™ Tech Days

Bean pool size does not exist 1) newInstance() 2) setSessioncontext()

EjbRemove()

3)ejbCreate()

method-ready pool Business method EJB Instance

79

The Sun's EJB Container

Push your development further

Sun™ 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

Push development Theyour Sun's EJBfurther Container

Sun™ 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:

81

–

Increase when observing excessive creation and deletion of bean instances

–

Decrease when accumulating a large number of instances in pool

Push development Theyour Sun's EJBfurther Container

Sun™ Tech Days

Configuring Pool and Cache

 Per bean: in ejb module’s sun-ejb-

jar.xml –

and

 Global defaults: in server instance’s

server.xml –

82

and

Push your development further JDBC Tips

Sun™ 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

Push your development further Database Performance

Sun™ 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

Push your developmentTips furtherSummary Performance

Sun™ 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

Push your development further Manage Expensive

Resources

Sun™ 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

Push your development further Design Patterns can Significantly Help Performance

 Session Facade  Service Locator  Value List Handler  Data Transfer Object

87

Sun™ Tech Days

Push your development further

Some JMS Messaging, J2EE Best Practices 88

Sun™ Tech Days

Sun™ Tech Days

Push your development further Point-to-Point

Example: Order and Fulfillment

Queue

JMS Java™ Pet Store

89

JMS

Sun™ Tech Days

Push your development further Publish and Subscribe

Example: Stock Price Changes

Topic Price Change

Traders/Brokers

90

Sun™ Tech Days

Push your development further Message-Driven Bean

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 Provider Desti Queue nation

91

MDB Consume Consumer r

Container Msg-

MDB driven Instances Instances

Bean

Msg-Driven Bean Class

Sun™ Tech Days

Push yourFacade development further MDB Pattern

Mailer MDB Asynchronous Message Delivery

Order Approval MDB

EJB Tier

LineItem Entity

Card Entity

1:m Purchase Order Entity Address Entity

 Use the MDB Facade:  provide a simple asynchronous interface to a complex

92

subsystem of enterprise beans

Push JMSyour development further

Sun™ 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

Push your development further

Tools Summary Resources 94

Sun™ Tech Days

Push your development further Use Tools

Sun™ 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

Push your development further 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

96

Sun™ Tech Days

Sun™ Tech Days

Push your development further Resources:

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

97

J2EE Performance Testing

Push your development further

Sridhar Reddy Technology Evangelist [email protected]

Sun™ Tech Days

98

Sun™ Tech Days