j 2 ee best practices

Upload: aminabenabdalah

Post on 04-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 j 2 Ee Best Practices

    1/102

    Push your development furtherSunTechDays

    J2EE Best Practices usingReal-life Examples.

    Carol McDonaldTechnology Evangelist

    [email protected]

    Sun Tech Days

  • 7/31/2019 j 2 Ee Best Practices

    2/102

    Push your development furtherSunTechDays

    eBay Architecture: How to Go

    Microsoft IIS

    eBayISAPI.dll

    MSXML

    to here?From there

    J2EE ContainerWeb Container

    Presentation Tier

    EJB Container

    Business Tier

    Integration Tier

    Services

    Configur

    ation

    Logging

    Secur

    ity

    Monolithic Proprietary

    Layered Loosely coupled Modular Standards based

  • 7/31/2019 j 2 Ee Best Practices

    3/102

    Push your development furtherSunTechDays

    What Is Needed

    Learning the technology is

    not enough

    Industry best practices

    Proven solutions

    How to avoid bad practices?

    Experience and expertise

  • 7/31/2019 j 2 Ee Best Practices

    4/102

  • 7/31/2019 j 2 Ee Best Practices

    5/102

    Push your development furtherSunTechDays

    Som e Web T ier

    Best Prac t ic esand Pat t erns

  • 7/31/2019 j 2 Ee Best Practices

    6/102

    Push your development furtherSunTechDays

    Layering

    EJB Session Beans

    Client Application

    Data Transfer Objects

    i.e. Managed Entity Values

    Business Logic Layer

    Service Layer

    Domain Layer

    Managed Entities

    Presentation Layer

    Network

    ManagedEntities

  • 7/31/2019 j 2 Ee Best Practices

    7/102

    Push your development furtherSunTechDaysRationale for Layers

    More flexible, extensible:

    Presentation Layers

    Frequent changes, designed to be flexible

    Business Services

    Implement use-cases Public interface, resource access

    Should remain valid for changes in presentationand data store

    Data Layers

    Fewer changes, designed to optimize data access

  • 7/31/2019 j 2 Ee Best Practices

    8/102

    Push your development furtherSunTechDays

    Layered View (cont.)

    Layered View helps to:

    Clearly divide responsibilities Decouple business logic completely

    Provide a common place for pre-processing and post-processing ofrequests and responses (like logging,translations, transformations, etc.)

    Expose a web service interface toexisting business logic

  • 7/31/2019 j 2 Ee Best Practices

    9/102

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

    View = view ofmodel,presents the user interface

    Controllermediates theirinteractions

  • 7/31/2019 j 2 Ee Best Practices

    10/102

    Push your development furtherSunTechDays

    Web Tier: Problem

    1. Request

    ???

    2. Response

    No centralized access pointfor presentation request handling

    Web Server

    Common RequestProcessingLogic?

    Duplicate common

    logic in ViewsClient

    View

    View

    View

  • 7/31/2019 j 2 Ee Best Practices

    11/102

    Push your development furtherSunTechDays

    Service to Worker

    CommandFactory

    FrontController

    Dispatcher

    CommandHelper

    1. Request

    3. Parse Request

    2. Common logic

    5. Create

    6. Execute

    8. Dispatch7. Business

    logic

    4. Get cmd

    ViewHelper

    DataBean

    View

    Client

    Servlet

    JSP

    Java Objects

    10. Response

    9. Get Data

  • 7/31/2019 j 2 Ee Best Practices

    12/102

    Push your development furtherSunTechDays

    Use an MVC Framework

    Faster, easier development of

    Request processing

    Response generation

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

  • 7/31/2019 j 2 Ee Best Practices

    13/102

    Push your development furtherSunTechDays

    Struts Framework

    View Controller Model

    JSPw/Struts

    Form Bean

    ActionServlet

    Action

    Bean

    Java

    Bean

    Struts-config.xml

    SessionBean(s)

    EntityBean(s)

    Browser

    Database

  • 7/31/2019 j 2 Ee Best Practices

    14/102

    Push your development furtherSunTechDaysStruts and Core J2EE Patterns

    Client

    ActionServlet

    Action

    ActionForward

    ActionForm

    JSP View

    Front Controller Model

    View HelperView

    ActionMapping

    (xml)

    ServiceInterface

    BusinessService

    BusinessDelegate

    ServiceLocator

    Command

    Dispatcher

    Response

    Request

    Uses

  • 7/31/2019 j 2 Ee Best Practices

    15/102

    Push your development furtherSunTechDays

    Ebay.com: Presentation Tier

    Request

    Response

    Client

    Business

    ServiceCommand

    Request Handler

    Intercepting

    Filter

    Front

    Controller

    Navigator Dispatcher

    Navigation and Dispatch

    View Processor

    TransformerHelper

    InterceptingFilter

    ViewProcessor

    Business

    Delegate

    ServiceLocator

    XML

    XSLCore J2EE

    Pattern

    Strategy

    Service Interface

  • 7/31/2019 j 2 Ee Best Practices

    16/102

    Push your development furtherSunTechDays

    Cache for Performance

    Some things can be cached and shared (singleton):

    InitialContext object

    Anything retrieved from JNDI, EJB Home interfaces

    Repeated lookups can be expensive! Use Service LocatorPattern

    Some things are cached by individual clients(session):

    Cache search results when you are only displaying a few

    at a time (non-transactional data) JDBC CachedRowSet

    Value List Pattern

  • 7/31/2019 j 2 Ee Best Practices

    17/102

    Push your development furtherSunTechDays

    Service Locator Pattern

    Use the Service Locator Pattern toCache references obtained by JNDI lookups

    (ejb references, datasources, jms)

    Repeated lookups can be expensive!

  • 7/31/2019 j 2 Ee Best Practices

    18/102

    Push your development furtherSunTechDaysBusiness Delegate

    Client

    independent fromejb tier

    Ejb detailshidden

    Mock objects can

    be used to testclient w/o ejb tier

  • 7/31/2019 j 2 Ee Best Practices

    19/102

    Push your development furtherSunTechDays

    Tips for Servlets

    Servlets are Multithreaded

    Avoid use of shared modified class variables

    Synchronize only small blocks in code

    Remove servlet sessions when they

    are no longer needed: In logoff call session.invalidate()

    On client side, dont access your EJBsdirectly, use service locator withbusiness delegate

  • 7/31/2019 j 2 Ee Best Practices

    20/102

    Push your development furtherSunTechDays

    Servlet Tips

    DO use high performance J2EE

    design patterns MVC, Service Locator

    DONT hold resources explicitlyfree them

    DONT intensively processimmutable objects.

  • 7/31/2019 j 2 Ee Best Practices

    21/102

    Push your development furtherSunTechDays

    Tips for JSPs

    Avoid scriptlets in JSP

    Use JSTL (JSP 2.0 Standard Tag Libraries):

    Pass data to JSP in Servlet request notsession

    If JSP does not use the HTTP session

    Use to preventHTTP Sessions from being automatically created

  • 7/31/2019 j 2 Ee Best Practices

    22/102

    Push your development furtherSunTechDays

    Som e EJ B Tier

    Best Prac t ic es

    and Pat t erns

  • 7/31/2019 j 2 Ee Best Practices

    23/102

    Push your development furtherSunTechDaysDo you need EJBs?

    Do you need declarativetransactional support?

    Do you need to distribute yourbusiness logic?

    Do you need JMS, JAX-RPC, RMI?

    Do you need to support multipleclient types?

    Do you need method-level securityon your objects?

    Do you need a standards-basedarchitecture?

  • 7/31/2019 j 2 Ee Best Practices

    24/102

    Push your development furtherSunTechDays

    Architecting Applications

    Functional requirements captured

    via use-cases

    Use-cases implemented using MVC &

    Command design patterns Implement Business Logic as a Service

  • 7/31/2019 j 2 Ee Best Practices

    25/102

    Push your development furtherSunTechDays

    Use case realization

    View Items

    Any User

    View Items

    Any user can view any itemsavailable for bidding or sale

  • 7/31/2019 j 2 Ee Best Practices

    26/102

    Push your development furtherSunTechDays

    AssembleData

    Use case

    Biz logic

    Convert toBiz Command

    CentralizeRequest Hndlg

    View Items Design Requirements

    RetrieveData

    Item/Auctionspecificbiz logic

  • 7/31/2019 j 2 Ee Best Practices

    27/102

    Push your development furtherSunTechDays

    ApplicationController

    FrontController

    SessionFacade

    BusinessDelegate

    View Items Design

    ServiceLocator

    ApplicationService

    TransferObject

    Assembler

    TransferObject

    Value ListHandler

    Data AccessObject

  • 7/31/2019 j 2 Ee Best Practices

    28/102

    Push your development furtherSunTechDays

    WEB Tier

    PresentationBusiness Logic &

    Messaging Fabric

    Data Integration

    & Persistence

    Core Application Design Patterns

    FRONT

    CONTROLLERVIEW

    COMMAND

    object

    Request Response

    MODEL

    DATA

    TRANSFER

    OBJECT

    BUSINESS

    SERVICE

    FACADE

    Value List Handler

    DATA

    ACCESS

    OBJECT

    DATA

    TRANSFER

    OBJECT

    SessionEJB

    Servlet

    JSP

    Java Objects

    Session EJB

  • 7/31/2019 j 2 Ee Best Practices

    29/102

    Push your development furtherSunTechDays

    Data Transfer Object

    A lot of network traffic

    Reduced network traffic

    with Data Transfer Object

    ClientObject CustomerEntityBean CustomerInfoEntityBean

    Before

    ClientObject

    CustomerEntityBean

    CustomerInfoEntityBean

    After

    GetCustomerInfo()

    GetCustomerInfo()

    GetCity()

    GetState()

    GetZipCode()

    GetCity()

    GetState()

    GetZipCode()

    Networkboundary

    Networkboundary

    Create()

    Create()

  • 7/31/2019 j 2 Ee Best Practices

    30/102

    Push your development furtherSunTechDays

    Value List Handler

    For querying, filtering, anddisplaying large amountsof data:

    Value List Handler handlesthe search, caches resultsand provides a filterableand traversable result set

    Client ValueListHandler

    ValueList ValueObject

    DataAccessObject

    Interface

    ValueListiterator

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

  • 7/31/2019 j 2 Ee Best Practices

    31/102

    Push your development furtherSunTechDays

    Sequence Diagram

    1: Create

    2: Execute Search

    3: Get Next

    4: Get Previous

    5: Get Current

    6: Get Size

    3.2: Return Sub-list

    4.2: Return Sub-list

    5.2: Return Value Object

    6.2: Return Size

    2.1: Execute Search

    2.1.2: Return Value List

    3.1: Get Sub-list

    4.1: Get Sub-list

    5.1: Get Current

    6.1: Get Size

    2.1.1: Create

    Client

    ValueListHandler

    DataAccessObject

    ValueList

    ValueListiterator

  • 7/31/2019 j 2 Ee Best Practices

    32/102

    Push your development furtherSunTechDays

    Data Access Object

    BusinessObject DataAccessObject DataSource

    ValueObject

    Uses Encapsulates

    creates/uses

    obtains/modifies

  • 7/31/2019 j 2 Ee Best Practices

    33/102

    Push your development furtherSunTechDays

    eBay.com: Business Tier

    Data

    Source

    Dispatch

    Application

    Controller

    BusinessLogic/Data

    TransferObject

    DAO

    ApplicationService

    Persistence

    ContextObject

    TransferObject

    Assembler

    BusinessObject

    ValueList

    Handler

    Domain

    Store

    Core J2EE

    Pattern

    Strategy

    Command

  • 7/31/2019 j 2 Ee Best Practices

    34/102

    Push your development furtherSunTechDays

    Direct Entity Bean access results in excessive network overhead

    and multiple transactions

    Dont:

    EJB

    Network

    Client

    Direct Bean Access

    Do:

    EJBNetwork

    Client

    Facade

    Session Facade pattern

  • 7/31/2019 j 2 Ee Best Practices

    35/102

    Push your development furtherSunTechDaysSession Facade pattern

    EntityBean 1

    EntityBean 2

    JavaObject

    DataAccess

    Object 2

    Data

    AccessObject 1

    1. doThis(...)

    2. getData()

    3. process

    2. getData()

    Session Bean

    Entity Bean

    Plain Java Object

    Use the Session Facade:

    To reduce network overhead

    To group related updates into transactions

    SessionFacade

    Client

    SessionBean

  • 7/31/2019 j 2 Ee Best Practices

    36/102

    Push your development furtherSunTechDaysContainer Managed Transactions

  • 7/31/2019 j 2 Ee Best Practices

    37/102

    Push your development furtherSunTechDays

    EJBclient

    EJBObject

    Network

    Local vs. Remote Interfaces

    Pass by Value:

    Serialize/deserializemethod parameters

    Pass by Reference:

    Better performance

    Remote Interfaces Local Interfaces

    EJBclient

    EJBObject

  • 7/31/2019 j 2 Ee Best Practices

    38/102

  • 7/31/2019 j 2 Ee Best Practices

    39/102

    Push your development furtherSunTechDays

    Session EJB tips

    Stateless session beans give best

    performance, watch use of stateful Remove stateful session beans to

    reduce unnecessary passivation

    Limit size of objects stored in session

    beans (performance for passivation)

  • 7/31/2019 j 2 Ee Best Practices

    40/102

    S

  • 7/31/2019 j 2 Ee Best Practices

    41/102

    Push your development furtherSunTechDays

    Design Patterns Summary

    Value 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/.

    S

  • 7/31/2019 j 2 Ee Best Practices

    42/102

    Push your development furtherSunTechDays

    Pers is tence

    Opt ions

    S

  • 7/31/2019 j 2 Ee Best Practices

    43/102

    Push your development furtherSunTechDays

    Data Access in J2EE

    Formal object-oriented model

    EJB container managed persistence Great choice for representing existing databases

    JDO

    Tabular access

    Plain JDBC

    JDBC RowSets

    Good choice for ease of development Non-relational, non-object data access

    Use J2EE Connectors

    Sun

  • 7/31/2019 j 2 Ee Best Practices

    44/102

    Push your development furtherSunTechDays

    BMP vs. CMP

    CMPBean

    EJB Container

    BMPBean

    EJB Container

    JDBC

    DriverJDBC

    SQLJ

    SQL

    JDBC

    Driver

    SQL

    PersistenceManager

    BeanState

    Database

    BeanState

    Database

    JDBC

    SQLJ

    1) Bean provider manages State and Data consistency

    2) Bean provider handles relationships and OR Mapping

    1) Container manages State and Data consistency

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

    Sun

    O

  • 7/31/2019 j 2 Ee Best Practices

    45/102

    Push your development furtherSunTechDays

    Use BMP or DAO for

    Dealing with legacy database and/or

    other persistence store Previously written complex application

    Connector driven data stores, EIS Efficient execution of complicated queries

    Bulk updates

    Complex joins

    Aggregates

    Sun

    E i B Ti

  • 7/31/2019 j 2 Ee Best Practices

    46/102

    Push your development furtherSunTechDays

    Entity Bean Tips

    Do not use EJB entity beans for batchloading or queries that return large result

    sets. Use Data Access Objetsencapsulating JDBC

    Use CMP rather than BMP entity beanwhen possible

    Do not call EJB entity bean get & setmethods from client

    Wrap with session beans to provide course

    grain access and single transaction context

    Sun

    JDBC Ti

  • 7/31/2019 j 2 Ee Best Practices

    47/102

    Push your development furtherSunTechDays

    JDBC Tips

    Select a certified, high performancetype 2 JDBC driver

    Tune connection pool size Close resources as soon as youre done

    with them (in finally)

    E.g. Statements, Connections, ResultSets

    Use JDBCs PreparedStatement instead

    of Statement when possible Turn off Auto-Commit

    Group updates into a transaction

    Sun

    JDBC Ti

  • 7/31/2019 j 2 Ee Best Practices

    48/102

    Push your development furtherSunTechDays

    JDBC Tips

    JDBC Supports a number of highperformance optimization techniques

    Typically you can optimize JDBCperformance by:

    Using CachedRowSets

    Using setDefaultRowPrefetch

    Using statically bound column types Using update batching

    Using statement caching

    Sun

    D t b P f

  • 7/31/2019 j 2 Ee Best Practices

    49/102

    Push your development furtherSunTechDays

    Database Performance

    Common performance bottleneck

    Typical problems: Inefficient queries - sending SQL data

    that asks the database to do more work

    than necessary Excessive querying - efficient queries

    called too frequently

    Large Data Sets - processing large setsof data in ResultSets

    fSun

    CMP 2 0 E tit B

  • 7/31/2019 j 2 Ee Best Practices

    50/102

    Push your development furtherSunTechDays

    CMP 2.0 Entity Beans

    java.io.Serializable

    CMP Entity Bean subclass

    (Contains persistence logic)

    CMP Entity Bean abstract class(Contains data handling logic)

    javax.ejb.EntityBean

    javax.ejb.EnterpriseBean

    You (bean provider)write this code.

    Container provides

    this class.

    Entity Bean is now anabstract class,container extends it

    h d l f hSun

    C t i M d R l ti hi

  • 7/31/2019 j 2 Ee Best Practices

    51/102

    Push your development furtherSunTechDays

    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

    P h d l f hSun

    A f CMP d CMR

  • 7/31/2019 j 2 Ee Best Practices

    52/102

    Push your development further TechDaysAccessors for CMP and CMR

    public abstract class OrderBeanimplements EntityBean {

    private EntityContext context;

    //access methods for cmp fields

    public abstract String getOrderID(); //primary keypublic abstract void setOrderID(String id);. . .

    //access methods for cmr fields

    public abstract Collection getLineItems();public abstract void setLineItems(Collection lineItems);

    P h d l t f thSun

    CMP 2 0 Relationship Handling

  • 7/31/2019 j 2 Ee Best Practices

    53/102

    Push your development further TechDaysCMP 2.0 Relationship Handling

    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-managedpersistent fields

    ... define EJB relationships ...

    P h d l t f thSun

    EJB QL Example

  • 7/31/2019 j 2 Ee Best Practices

    54/102

    Push your development further TechDays

    EJB QL Example

    Find orders for a specific product:

    SELECT OBJECT(o)

    FROMOrders o, IN(o.lineItems)lWHERE l.product.name = ?1

    XML:

    findByProduct

    LocalHome SELECT OBJECT(o) FROM Order o,IN (o.lineItems) l WHERE I.product.name= ?1

    P h d l t f thSun

    Advantages of CMP 2 0

  • 7/31/2019 j 2 Ee Best Practices

    55/102

    Push your development further TechDays

    Rich modeling capability on relationships- container manages the relationships,

    not you! Referential integrity

    Cardinality Cascading delete

    Freedom from maintaining interactionswith the data store

    EJB Query Language (EJB QL)

    Portable code

    Advantages of CMP 2.0for developer

    P h d l t f thSun

  • 7/31/2019 j 2 Ee Best Practices

    56/102

    Push your development further TechDays

    CMP

    P sh o r de elopment f rtherSun

    Advantages of CMP 2 0

  • 7/31/2019 j 2 Ee Best Practices

    57/102

    Push your development further TechDays

    Optimization is possible becausepersistent fields are only accessible

    via get and set methods Lazy loading

    Dirty checking Optimistic locking

    Optimization is possible in query

    operation

    Because Query is defined in deployment

    descriptor via EJB QL

    Advantages of CMP 2.0for Container

    Push your development furtherSunT h

    CMP Optimizations

  • 7/31/2019 j 2 Ee Best Practices

    58/102

    Push your development further TechDays

    CMP Optimizations

    Aggressive Loading

    Loading fields relationships and fields ofchildren in the same query

    Lazy Loading

    Deferring loading of any data until it is accessed

    Dirty Writes

    Only update data which has been changedin the database

    Push your development furtherSunT h

    CMP: Standard Vs

  • 7/31/2019 j 2 Ee Best Practices

    59/102

    Push your development further TechDays

    Standard features

    Declarative specification of:

    Persistent attributes, abstract schema, relationships,queries for finder/select methods(via EJBQL),

    transactional attributes

    Vendor specific

    O/R mapping, concurrency and consistencysemantics, caching semantics, performanceand usability

    CMP: Standard Vs.Vendor Specific Features

    Push your development furtherSunT h

    Pessimistic Locking

  • 7/31/2019 j 2 Ee Best Practices

    60/102

    Push your development further TechDays

    Pessimistic Locking

    Time State inDatabase

    1000

    200020002000

    3000 3000

    C2C1

    The row is locked for the duration of the transaction

    1000

  • 7/31/2019 j 2 Ee Best Practices

    61/102

    Push your development furtherSunTech

    Usage Guidelines

  • 7/31/2019 j 2 Ee Best Practices

    62/102

    Push your development further TechDays

    Usage Guidelines

    Pessimistic

    Serialized access Recommended for

    beans where

    conflicts are boundto happen

    Scalability dependson DB and Appserver lockinggranularity

    Optimistic

    Concurrentaccess

    Large-scale

    deployment Requires collision

    and exceptionhandling

    Choices forconflict detection

    Push your development furtherSunTech

    Data and Caching

  • 7/31/2019 j 2 Ee Best Practices

    63/102

    Push your development further TechDays

    Data and Caching

    Static data Keep a local copy, hang on to it in memory,

    dont worry about being stale

    Near static data

    Keep a local copy, hang on to it in memory,

    lazily check for updates

    Dynamic data

    Work on local copy, cache carefully, useoptimistic locking

    Hot data

    Pessimistic locking

    Push your development furtherSunTech

    Database Isolation Modes

  • 7/31/2019 j 2 Ee Best Practices

    64/102

    Push your development further TechDays

    Database Isolation Modes

    Read Uncommitted Dirty reads, non-repeatable reads and

    phantom reads can occur

    Read Committed Dirty reads are prevented; non-

    repeatable reads and phantom reads

    can occur Repeatable Read

    Dirty reads and non-repeatable reads

    are prevented; phantom reads canoccur

    Serializable Dirty reads, non-repeatable reads and

    phantom reads are prevented

    Push your development furtherSunTech

    Entity Bean Caching

  • 7/31/2019 j 2 Ee Best Practices

    65/102

    Push your development further TechDays

    Entity Bean Caching

    Commit Option A At the end of the transaction, the instance stays

    ready and the instance state is valid Commit Option B

    At the end of the transaction, the instance stays

    ready but the instance state is NOT valid Commit Option C

    At the end of the transaction, neither the instance

    nor its state is valid Best Option: Check your app server

    Push your development furtherSunTech

    Transaction Do's

  • 7/31/2019 j 2 Ee Best Practices

    66/102

    Push your development further TechDays

    Transaction Do s

    Do use READ_COMMITTED withOptimistic locking as much as possible

    Do use Optimistic locking only andSERIALIZABLE if required.

    Push your development furtherSunTech

    Transaction Don'ts

  • 7/31/2019 j 2 Ee Best Practices

    67/102

    Push your development further TechDays

    Transaction Don ts

    Don't use SERIALIZABLE if itcan be avoided

    Don't use pessimistic locks if itcan be avoided

    Push your development furtherSunTech

    EJB Summary

  • 7/31/2019 j 2 Ee Best Practices

    68/102

    Push your development further TechDays

    EJB Summary

    EJB Container Services use appropriately for: Distributedtransactionmanagement

    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.

    Push your development furtherSunTech

  • 7/31/2019 j 2 Ee Best Practices

    69/102

    Push your development furtherDays

    J2EE

    Per formanceTips

    Push your development furtherSunTech

    Tune App Server

  • 7/31/2019 j 2 Ee Best Practices

    70/102

    Push your development furtherDays

    Tune App Server

    Execute threads that requests run on

    JDBC connection pools

    JDBC prepared statement cache size

    Correct settings depend on application

    Push your development furtherSunTech

    Tune Key Container Parameters

  • 7/31/2019 j 2 Ee Best Practices

    71/102

    Push your development furtherDays

    Tune Key Container Parameters

    Session timeouts

    Stateful session bean and entity beancache

    Cache = EJB instances with state

    Stateless session and entity bean pools

    Pool = EJB instances with no assigned state

    Transaction isolation level

    Push your development furtherSunTech

    Entity Bean

  • 7/31/2019 j 2 Ee Best Practices

    72/102

    Push your development furtherDaysEntity Bean

    Does

    not exist

    pooled

    ready

    NewInstance()

    setEntityContext() unsetEntityContext()

    ejbCreate()

    ejbPostCreate()ejbRemove()

    business method

    ejbStore()ejbLoad()

    ejbFind()

    ejbActivate() ejbPassivate()

    EjbActivate()

    EJB

    Instance

    EJB

    Object

    EJBInstance

    Bean pool sizeBean cache size

    Push your development furtherSunTech

    Stateful Session Bean

  • 7/31/2019 j 2 Ee Best Practices

    73/102

    us you de elop e t u t eDaysStateful Session Bean

    Method-ready

    ejbRemove()

    business method

    does not

    exist

    1) newInstance()

    2) setSessioncontext()

    3)ejbCreate() ejbPassivate()

    EjbActivate()

    passiveEJBInstance

    EJB

    Object

    Bean cache sizeSession time out

    Push your development furtherSunTech

    Stateless Session Bean

  • 7/31/2019 j 2 Ee Best Practices

    74/102

    y pDays

    EJBInstance

    method-ready

    pool

    EjbRemove()

    Business method

    does not

    exist

    1) newInstance()

    2) setSessioncontext()

    3)ejbCreate()

    Stateless Session Beanand Message Driven Bean

    Bean pool size

    Push your development furtherSunTechD

    Manage Expensive Resources

  • 7/31/2019 j 2 Ee Best Practices

    75/102

    y pDaysManage Expensive Resources

    Cache EJB homes

    Cache data sources Minimize use of HTTP sessions

    Release database connections Removeunused stateful session beans

    Use local Interfaces

    Push your development furtherSunTechD

    Design Patterns can

  • 7/31/2019 j 2 Ee Best Practices

    76/102

    y pDays

    Session Facades

    Service Locator

    Value List Handler Data Transfer Object

    Design Patterns canSignificantly Help Performance

    Push your development furtherSunTechD

  • 7/31/2019 j 2 Ee Best Practices

    77/102

    y pDays

    Per formance

    Test ing

    Push your development furtherSunTechDays

    Performance Tips Summary

  • 7/31/2019 j 2 Ee Best Practices

    78/102

    y pDays

    Performance Tips Summary

    Tips for better performance Tune app server and infrastructure

    Leverage proven design patterns Design coarse grain EJB interfaces: Value Object

    Reduce JNDI look-ups: service locator Use session bean wrappers: session facade

    Database access Use JDBC for:

    Batch loading: session bean or message bean

    Large result sets: value list handler Use CMPrather than BMP Entity Beans Use right isolation level and database

    transactional control (locking)

    Push your development furtherSunTechDays

  • 7/31/2019 j 2 Ee Best Practices

    79/102

    Days

    JMS,

    Messaging,

    Web Serv ic esJ 2EE Best

    Prac t i ces

    Push your development furtherSunTechDays

    JMS

  • 7/31/2019 j 2 Ee Best Practices

    80/102

    Days

    Use JMS forloosely coupledapplications that need reliable,scalabledocument orientedmessage exchange

    Including Message-DrivenBeans and JMS in your J2EEapplication can greatly increase

    performance, robustness, andefficiency

  • 7/31/2019 j 2 Ee Best Practices

    81/102

    Push your development furtherSunTechDays

    Publish and Subscribe

  • 7/31/2019 j 2 Ee Best Practices

    82/102

    Days

    Traders/Brokers

    Price Change

    Topic

    Example: Stock Price Changes

    Push your development furtherSunTechDays

    Message-Driven Bean

  • 7/31/2019 j 2 Ee Best Practices

    83/102

    Daysg

    Container

    Destin-

    ation

    Consumer

    Msg-

    drivenBean

    Instances

    High Scalability, High Throughput

    MDB instances are pooled by the container

    Allow forasynchronous concurrent message consumptionfrom the same destination

    JMSProvider

    Container

    Queue

    MDB

    Consumer

    MDB

    Instances

    Msg-DrivenBean Class

    Concurrent Asynchronous Processing

  • 7/31/2019 j 2 Ee Best Practices

    84/102

    Push your development furtherSunTechDays

    MDB Facade Pattern

  • 7/31/2019 j 2 Ee Best Practices

    85/102

    Days

    EJBTier

    Relationship

    Reference

    AddressEntity

    Order

    ApprovalMDB

    LineItemEntity

    Mailer MDB

    CardEntity

    AsynchronousMessageDelivery

    PurchaseOrder Entity

    1:m

    Push your development furtherSunTechDays

    XML Message Facade

  • 7/31/2019 j 2 Ee Best Practices

    86/102

    yg

    EJB Architectural Pattern

    ClientJMS

    Queues

    MessageDrivenBean

    Stateless

    Session

    EJB

    Entity

    Bean

    XML Messaging Facade

    Asynchronous Synchronous

    Example implementation of XML interaction modelon top of Java interaction model

    Entity

    Bean

    Entity

    Bean

    XMLValue

    ObjectsJavaValueObjects

    Push your development furtherSunTechDays

    MDBs Container

  • 7/31/2019 j 2 Ee Best Practices

    87/102

    y

    Order

    Bean

    InventoryManagement

    Bean

    Mail

    MessageDrivenBean

    JMS Topics

    Publish/subscribe

    ProcessOrder

    ProcureInventory

    PurchaseOrder

    Queue

    TRANSACTION

    Managed Transactions

    Push your development furtherSunTechDays

    Use JMS for

  • 7/31/2019 j 2 Ee Best Practices

    88/102

    y

    Designing for event-driven interactions:

    Not interface-driven

    Loose coupling among participants

    Asynchronous communication model

    Reliable communication or many to manycommunication model

    Serves as an asynchronous facade to asubsystem or an application

    Event-Driven Interactions

    Push your development furtherSunTechDays

    MDB Join Pattern

  • 7/31/2019 j 2 Ee Best Practices

    89/102

    Join pattern MDB collects different messages

    Stores to same set of entity beans

    SetupOffice

    HumanResources

    ReserveOffice

    ReserveEquipment

    Add toPayroll

    Happy New Hire

    NewHire

    Assigned Office

    Equipment Info

    Furnished Office

    Paycheck

    Push your development furtherSunTechDays

    Example Problem Tracking

  • 7/31/2019 j 2 Ee Best Practices

    90/102

    ExistingSynchronousClient

    Access

    ProblemSolver

    Problem

    Rep

    Company

    EJB Tier

    A Session EJB provides thebusiness logic for the Customersor help desk to synchronouslyenter Problem data, or search forsimilar problems

    Entity EJBs provide the businesslogic for accessing/updating thedomain Data objects

    Push your development furtherSunTechDays

    Extension Solution Internal View

  • 7/31/2019 j 2 Ee Best Practices

    91/102

    RemoteHelp DeskNew

    Problem

    MonthlyReport

    ExistingSynchronousClient

    Access

    ReportRequest

    ProblemHandler

    ReportGenerator

    ProblemSolver

    Problem

    Rep

    Company

    EJB Tier

    Push your development furtherSunTechDays

    JMS Do's & Don'ts

  • 7/31/2019 j 2 Ee Best Practices

    92/102

    Do watch message size

    Do only use XML when necessary(lower performance)

    Do only use reliable messaging whennecessary (lower performance)

    Push your development furtherSunTechDays

    Tips for XML messaging

  • 7/31/2019 j 2 Ee Best Practices

    93/102

    Inside your Application dont overuse XML Parsing and processing can cause a performance

    hit Use XML for messages between

    systems

    Within a system just use data objects

    Convert the data from XML into a Javaclass as soon as possible Can use JAXB for this

    Use XML mainly for transmission

    Push your development furtherSunTechDays

    Key Web Service Guidelines

  • 7/31/2019 j 2 Ee Best Practices

    94/102

    Structure application in two layers Interaction layer and processing layer

    Interaction layer Interface to clients

    Receive requests and perform

    required translations andtransformations

    Delegate request to processing

    layer for processing Respond to clients

    ServiceClient

    Interaction

    Layer

    ProcessingLayer

    Push your development furtherSunTechDays

    Layered View

  • 7/31/2019 j 2 Ee Best Practices

    95/102

    Processing layer Process request

    Apply business logic

    Integrate with EIS

    Interact with peers

    Layered view helps to: Clearly divide responsibilities

    Decouple business logic completely

    Expose a web service interface to existingbusiness logic

    Push your development furtherSunTechDays

    RPC Simple Client/Service

  • 7/31/2019 j 2 Ee Best Practices

    96/102

    Common approaches:

    SOAP using JAX-RPC (WSDL) Features:

    Stateless and conversation-less Industry examples:

    Amazon, Fedex, eBay, credit check,

    get Weather, get Stock price

    Client ServiceRequest

    Response

    Push your development furtherSunTechDays

    RPC Style Web Services

  • 7/31/2019 j 2 Ee Best Practices

    97/102

    RDBMSEAI ResourceAdapters

    LegacySystems

    DataBase

    ERP

    Business

    Services

    Web

    Container

    Domain

    Objects

    WebComponent

    EntityEJB

    StatelessSession

    EJB

    DAO

    Connector

    MDB

    JAX-RPC

    Push your development furtherSunTechDays

    Collaborative B2B Web Services

  • 7/31/2019 j 2 Ee Best Practices

    98/102

    Features: Orchestration, Choreography, Collaboration

    Business process defines Message sequence

    Asynchronous document exchange

    Industry examples:

    OTA, Sabre, GM

    Business

    Process

    Service

    Service

    Service

    Service

    Push your development furtherSunTechDays

    Document Style Web Services

  • 7/31/2019 j 2 Ee Best Practices

    99/102

    RDBMSEAI ResourceAdapters

    LegacySystems

    DataBase

    ERP

    BusinessServices

    SoapHandler

    DomainObjects

    EntityEJB

    MDB DAO

    Connector

    MDB

    Soap

    MessageServices

    EntityEJB

    MDB

    SessionEJB

    SessionEJB

    BusinessDocument

    MsgServiceHandler

    Push your development furtherSunTechDays

    JBI and J2EE

  • 7/31/2019 j 2 Ee Best Practices

    100/102

    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/Servlet

    API)

    JMS

    MQ

    JCA

    Push your development furtherSunTechDays

    Sun ONE BPM, Messaging & J2EE

  • 7/31/2019 j 2 Ee Best Practices

    101/102

    XML/SOAP/JMS

    Business Process Engine

    Data

    XML Proxy

    Rule

    Base

    (XSLT)

    XSLTEngine

    MessageBroker

    Adapter

    C++

    Inventory

    Rule

    Base

    (XSLT)

    XSLT

    Engine

    Message

    Broker

    JMSProvider

    MDBServlets

    EJBJ2EE

    SOAP

    WebService

    Push your development furtherSunTechDays

  • 7/31/2019 j 2 Ee Best Practices

    102/102

    Carol McDonaldTechnology Evangelist

    [email protected]

    Sun Tech Days