Best+Practices+to+Improve+Performance+in+Servlets

  • Upload
    md-imam

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    1/97

    Best Practices to improve performance inServlets

    Overview of Servlets

    Servlets represent an extension to the HTTP server. It takes http request as an input andsends the http response to the client as an output. Servlet API provides two packages they are

    javax.servlet and javax.http.servelt. These packages contain interfaces and classes to dealwith generic and http functionality that eans you can write a Servlet in java to get httprequest and send a http response to the client. !lient is typically a "rowser. These interfacesare ipleented "y Servlet #ngines. There are nuerous vendors who provide Servlet#ngines to work with Servlets$ for exaple Tocat$ we"logic$ we"shpere etc.

    Servlet is loaded into the eory "y Servlet #ngine and it calls init%& ethod on first requestand then onwards only service%& ethod is called for every other request "y creating aseparate thread for each request and finally destroy%& ethod is called when the Servlet isreoved "y the Servlet #ngine. Service%& ethod can "e replaced "y do'et%& or doPost%&

    ethod.

    (ote that this architecture is a ulti threaded odel which is generally followed in ost of theapplications. )ou can even work with single threaded odel "y ipleentingSingleThread*odel interface where the Servlet #ngine creates a separate Servlet instance foreach request.

    (ote+, This is "rief explanation of Servlet architecture. -or ore inforation on Servlets$ seeavaila"le "ooks and online tutorials on Servlets.

    (ote, This Section assues that reader has soe "asic knowledge of Servlets.

    Use init() method as cache

    The default echanis of a Servlet #ngine is to load a Servlet in ultithreaded enviroent. Inthis environent$ a Servlet init%& ethod is called only once in its life tie. )ou can iproveperforance using init%& ethod. )ou can use this ethod to cache static data.

    'enerally a Servlet generates dynaic data and static data. Prograers often ake a istake"y creating "oth dynaic and static data fro service%& ethod. /"viously there is a reason tocreate dynaic data "ecause of its nature "ut there is no need to create static data every tie forevery request in service%& ethod.

    -or exaple$ norally you would write a Servlet like this

    pu"lic void service%HttpServlet0equest req$ HttpServlet0espnse res& throwsServlet#xception$I/#xception 1

    res.set!ontentType%2text3htl4&5

    Printwriter out 6 req.get7riter%&5

    out.print%89htl:4&5

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    2/97

    out.print%89head:9title:Hello world93title:93head:4&5

    out.print%29"ody:4&5

    33 send the dynaic data here

    out.print%293"ody:4&5

    out.print%893htl:4&5

    ;

    Here you are generating "oth static data and dynaic data. Instead you can odify the code asshown "elow

    pu"lic class servlet extends HttpServlet 1

    "yte

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    3/97

    Servlet/utputStrea out 6 res.get/utputStrea%&5

    out.write%header&5

    out.write%nav"ar&5

    33 write dynaic data here

    out.write%footer&5

    ;

    Here the static data is created in init() method which means that it is created only once in the life time ofServlet and it is used in service() method to pass the data to the client. When you send a large amount of

    static data then you can use this techni!ue to see a considerable increase in performance.

    Optimization techniques in service() method

    7hen you write a service%& ethod for your Servlet$ you can iprove perforance "y usingfollowing techniques.

    +. se String?uffer rather than using B operator when you concatenate ultiple strings

    . se print%& ethod instead of println%& ethod

    C. se Servlet/utputStrea instead of Print7riter

    D. Initiali@e the Print7riter with proper si@e

    E. -lush the data partly

    F. *inii@e the aount of code in the synchroni@ed "lock

    G. Set the content length

    +. se String?uffer for concatenation rather than using B operator when you concatenate

    ultiple strings. See Concatenating Strings for detailed inforation.

    . println%& ethod internally calls print%& ethod and there is no need for new line separationwhen generating htl pages. So a sall overhead of calling one ore ethod is reduced ifyou use print%& ethod directly.

    C. There is a sall overhead involved in Print7riter "ecause it is eant for character outputstrea and it encodes data to "ytes$ rather you can directly use Servlet/utputStreawhenever you want to send "inary data.

    D. The "etter way of creating Print7riter is

    ?yteArray/utputStrea "yteArray 6 new ?yteArray/utputStrea%+&5

    Print7riter out 6 new Print7riter%"yteArray&5

    This increases the si@e of "uffer in the Print7riter.

    E. If you want to pass the large data to the client fro your servlet$ user ay need to wait tillthe Servlet/utputStrea or Print7riter flushes the data. This happens generally whenever

    http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm#Strings104http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm#Strings104
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    4/97

    you have a nu"er of gifs per page that you want to pass to the client. The "etter approach isto flush the data partly using flush%& ethod rather than flushing whole data at a tie. )ou caninitially flush header$ then navigation "ar$ then "ody content and finally footer so that the userneed not wait for whole data and he sees the header data iediately and so on withnavigation "ar$ "ody content and footer.

    Servlet/utputStrea out 6 res.get/utputStrea%&5

    out.write%header&5

    out.flush%&5 33 flush the header

    out.write%nav"ar&5

    out.flush%&5 33 flush the navigation "ar

    33 write dynaic data here

    out.flush%&5 33 flush the dynaic data

    out.write%footer&5

    out.flush%&5 33 finally flush the footer

    F. *inii@e the aount of code in the synchroni@ed "lock that is used in the service ethodwhenever you want to the data to "e thread safe.

    for exaple$ you ay write like this

    synchroni@ed%this&1

    code line+5

    code line5

    code lineC5

    code lineD5

    ;

    ?ut here you ight want to synchroni@e the data in the code line instead of all the lines sothe "etter way is

    code line+5

    synchroni@ed%this&1code line5;code lineC5

    code lineD5

    This reduces the overhead of locking all the code lines.

    G. 7henever the client$ such as a "rowser requests a page it esta"lishes socket connectioninternally with the we" server to get the requested content. !lient gets the page data withultiple connections depending on the si@e of the data. If the data is ore$ such as with

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    5/97

    ultiple gifs then it needs to esta"lish ultiple connection to get the data. The nu"er ofconnections esta"lished will depend upon default content length of the header$ and si@e of thecontent to "e traversed fro we" server to the client. ?y increasing content length$ you canreduce traffic and increase the perforance. Here is an exaple

    response.set!ontentength%int contentSi@e&5

    This ethod sets the length of the content that the server can send to client "y using !ontentJength header.

    Optimization techniques in destroy() method

    The destroy%& ethod is called only once in its servlet life tie when the Servlet #nginereoves fro eory. It is always "etter to reove instance varia"le resources such asK>?! connections$ sockets and other physical resources in this ethod. to avoid eoryleaks.

    Cache the static and dynamic data

    The use of caching in different areas of your application gives very good perforance.

    'enerally every applicationLs data"ase schea will have at least soe read only ta"les. Thereis no need of accessing these ta"les every tie. )ou can cache that data in eory andreuse it instead of accessing data"ase every tie. It reduces network traffic$ consues less!P cycles and gives good perforance.

    !aching can "e done in three flavors naely static data caching$ sei dynaic data cachingand dynaic caching. Static data eans that the data doesnLt change in its life tie$ it alwaysconstant. Sei dynaic data eans that the data changes "ut not often. -or exaple thedata that changes after every one hour can "e called as sei dynaic data$ the data does notchange for every request. >ynaic data eans that it changes the data for every request./ften people use the word dynaic data for sei dynaic data as well. So even I followed thesae terinology. In this section$ dynaic data is synonyous with sei dynaic data.

    It is "est to cache static data and dynaic data in order to iprove perforance. 7e will

    discuss a few caching techniques to iprove Servlet perforance. They are as follows+. tili@ing ?rowser caching

    . !aching dynaic data at the server

    C. tili@ing application server caching facilities

    D. tili@ing Servlet APILs "uilt in facility$ HttpSession and Servlet!ontext o"jects

    As we saw a"ove$ !aching at init%& ethod is useful for caching static data and it reduces thecreation tie of static data for every request "ut any way finally we are passing data to theclient on every request. This type of caching is useful when you want to pass "oth static dataand dynaic data to the client. /ne ore caching technique is utili@ing the "rowser cache andalso cache the content at the server$ this can "e done "y avoiding a call to service%& ethod ifthe output content is not changed. This technique is achieved "y ipleentinggetast*odified%& ethod of HttpServlet class.

    7e" servers send the response with a LastJ*odifiedL header which tells the client when thepage was last changed. 7e" "rowser sends a request with LIfJ*odifiedJSinceL header whichtells we" server when it last downloaded the page. 7ith this counication server can predictwhether the file has changed or not$ if not it sends response with L(ot *odifiedLJCMD statuscode so that the "rowser uses its cache page instead of downloading fresh page. In order totake advantage of this technique$ Servlet should ipleent the getast*odified%& ethod totell the servlet engine a"out last odified tie. This ethod returns tie in illiseconds.

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    6/97

    -or ipleentation of this technique. See$

    http,33www.servlets.co3soap"ox3freecache.htl

    The third technique is that your application server ay support caching facility for dynaicdata. All you need to do is that configure the caching properties file which is supported "y yourserver. )ou can give what Servlet you need to cache and session tie out value to reove

    cache content. -or exaple 7e"sphere application server supports this type of facility. Havea look at this link

    http,33wwwJD.i".co3software3we"servers3appserv3doc3vCE3ae3infocenter3was3MFMFMMMDM+.htl

    The fourth technique is that you can use Servlet APILs HttpSession and Servlet!ontext o"jectsfor caching. HttpSession o"ject is availa"le for a user session across ultiple requests andServlet!ontext o"ject is availa"le for all the users using the application. )ou can setcachea"le o"jects into these o"jects and get those o"jects whenever you require within theirscope. The ethods that support caching are,

    Servlet!ontext.setAttri"ute%String nae$ /"ject cachea"le/"ject&5

    Servlet!ontext.getAttri"ute%String nae&5

    HttpSession.setAttri"ute%String nae$ /"ject cachea"le/"ject&5

    HttpSession.getAttri"ute%String nae&5

    Choosing the right session mechanism

    7e use session echanis to aintain client state across ultiple pages. The session startswhen the client$ such as "rowser requests for a 0 fro the we" server and it ends whenthe we" server ends the session or we" server ties out the session or user logs out or usercloses the "rowser.

    There are few approaches availa"le to aintain the session$ they are using

    +. HttpSession provided "y servlet API

    . Hidden fields

    C. !ookies

    D. 0 rewriting

    E. Persistent echanis

    /"viously it is difficult to select one echanis out of a"ove entioned approaches toaintain session data. #ach one ipacts perforance depending on aount of the data to "estored as session data and nu"er of concurrent users.

    The following ta"le gives you an idea of perforance "ased on the approach used.

    Session mechanism Performance escription

    HttpSession goodThere is no liit on si@e ofkeeping session data

    Hidden fields oderateThere is no liit on si@e ofpassing session data

    !ookies oderate There is a liit for cookie si@e

    0 rewriting oderateThere is a liit for 0rewriting

    http://www.servlets.com/soapbox/freecache.htmlhttp://www-4.ibm.com/software/webservers/appserv/doc/v35/ae/infocenter/was/0606000401.htmlhttp://www-4.ibm.com/software/webservers/appserv/doc/v35/ae/infocenter/was/0606000401.htmlhttp://www.servlets.com/soapbox/freecache.htmlhttp://www-4.ibm.com/software/webservers/appserv/doc/v35/ae/infocenter/was/0606000401.htmlhttp://www-4.ibm.com/software/webservers/appserv/doc/v35/ae/infocenter/was/0606000401.html
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    7/97

    Persistent echanis oderate to poorThere is no liit of keepingsession data

    Here the Persistent echanis eans that you store the session data in the data"ase$ filestorage or any other persistent storage. There are few a approaches for this echanis$ theyare

    +. sing your application serverLs persistent echanis for session data storage

    . sing your own persistent echanis "y aintaining your own data"ase schea

    If you use the first approach$ generally application server converts the session o"jects into?/? data type and stores in the data"ase. If you use second approach$ you need to designthe schea as per your session fields and need to store the session data "y writing K>?!code for that$ this gives "etter perforance than the first approach "ecause conversion ofsession o"ject to ?/? takes ore tie than directly storing session data. #ither of persistentechaniss give oderate to poor perforance when copared to other approaches"ecause of overhead involved in data"ase calls through K>?! and it akes calls to data"aseon every request in order to store that session data and finally it needs to retrieve the wholesession data fro data"ase "ut it scales well on increasing session data and concurrentusers.

    0 rewriting gives oderate perforance "ecause the data has to pass "etween the clientand server for every request "ut there is a liitation on aount of data that can "e passedthrough 0 rewriting. It gives oderate perforance "ecause of overhead involved innetwork for passing data on every request.

    !ookies also give oderate perforance "ecause they need to pass the session data"etween client and server. It also has the si@e liit of Dk for each cookie.

    ike 0 rewriting and !ookies$ Hidden fields need to pass the data "etween client andserver. All these three session echaniss give oderate perforance and is inverselyproportional to the aount of session data.

    HttpSession echaniss gives "etter perforance when copared to other echanis"ecause it stores the session data in eory and reduces overhead on network. /nly sessionid will "e passed "etween client and the server. ?ut it does not scale well when the sessiondata is huge and the concurrent nu"er of users are ore "ecause of increase in eoryoverhead and also increase in overhead on gar"age collection.

    0ee"er that choosing the session echanis fro one of the a"ove approaches is notonly depends on perforance$ scala"ility and security. The "est approach is to aintain a"alance "etween perforance$ security and scala"ility "y choosing a ixed approache.*ixture of HttpSession echanis and Hidden fields gives "oth perforance and scala"ility.?y putting secure data in HttpSession and non secure data on hidden fields you can achieve"etter security.

    Control !ttpSession

    If you decided to use HttpSession for your session tracking$ then you need to know how your

    application server3servlet engine ipleents HttpSession echanis. )ou need to take careof the following points.

    +. 0eove session explicitly

    . Set Session tie out value

    C. Application server3servelt engine ipleentation

    'enerally$ your application server3servlet engine will have default session tie out value as CMinutes which eans that if you donLt reove session or anipulate that session for CM

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    8/97

    inutes then your servlet engine reoves that session fro eory. If you set long sessiontie out value such as + hour$ then it keeps all the session o"jects till + hour. This approacheffects scala"ility and perforance "ecause of overhead on eory and gar"age collection.In order to reduce eory overhead and to increase perforance$ it is "etter toreove3invalidate session explicitly using HttpSession.invalidate%& ethod. and also try toreduce the session tie out value as per your applicationLs requireent.

    Third iportant point is that your application server ay seriali@e session o"jects aftercrossing certain eory liit$ It is expensive and effects perforance "ecause it not onlyseriali@es the single session o"ject "ut also seriali@es the total o"ject hierarchy. se LtransientLfor varia"les to avoid unnecessary seriali@ation. see Seriali@ationfor detailed inforation toiprove perforance. So know a"out your application server3servlet engine sessionipleentation echanis and act accordingly.

    isa"le Servlet auto reloading

    *ost of the application servers3servlet engines have the capa"ility of loading servletsdynaically$ that eans you need not restart your server whenever you change the servletcontent. Application server3servlet engine loads the servlet with auto reload each tie whenyou configure the servlet. -or exaple$ if you configure auto reload as + second$ then servletengine loads that servlet after every + second. This feature is good at developent tie

    "ecause it reduces the developent tie "y avoiding restarting the server after every changein servlet. ?ut it gives poor perforance at production "y unnecessary servlet loading and"urden on class loader. So turn off your auto reloading feature in the configuration file toiprove perforance.

    Control #hread pool

    Servlet engine creates a separate thread for every request and assigns that thread to service%&ethod in its ultithreaded servlet and finally it reoves that thread after copletion ofservice%& ethod execution. It happens for every request. )our servlet engine ay create anew thread for every request "y default. This default "ehavior reduces perforance "ecausecreating and reoving threads is expensive. This can "e avoided "y using the thread pool.Servlet engine creates pool of threads at start up and assigns a thread fro pool to everyrequest instead of creating a fresh thread every tie and it returns that thread to the pool after

    copletion. The si@e of the thread pool depends upon configuration paraeters of the pool.The pool will have iniu and axiu nu"er of threads and you can configure thesenu"ers in the configuration file of your servlet engine. The nu"er of axiu andiniu threads in pool depend upon concurrent users for your application. )ou have toestiate nu"er of concurrent users for your application and give the thread pool si@e "asedon that. /"viously there is a liit on thread pool which depends on your hardware resources.?y setting thread pool si@e correctly$ The perforance of servlet iproves significantly. )ourapplication server3 KSP engine ay not have facility to configure thread pool. TocatLs Servlet#ngine has the facility to configure thread pool. ook at your application server 3 servletengine docuentation for inforation a"out thread pool.

    $ey Points

    +. se init%& ethod to cache static data. se String?uffer rather than using B operator when you concatenate ultiple stringsC. se print%& ethod rather than println%& ethodD. se Servlet/utputStrea rather than Print7riter to send "inary dataE. Initiali@e the Print7riter with proper si@eF. -lush the data partlyG. *inii@e code in the synchroni@ed "lock. Set the content lengthN. 0elease resources in destroy%& ethod.

    http://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2se/Serialization.htm
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    9/97

    +M. Ipleent getast*odified%& ethod to use "rowser cache and server cache++. se application server caching facility+. se *ixed session echaniss such as HttpSession with hidden fields+C. 0eove HttpSession o"jects explicitly in your progra whenever you finish the task+D. 0educe session tie out value as uch as possi"le+E. se LtransientL varia"les to reduce seriali@ation overhead if your HttpSession tracking

    echanis uses seriali@ation process.+F. >isa"le servlet auto reloading feature.

    +G. se thread pool for your servlet engine and define the si@e as per applicationrequireent.

    Best Practices to improve Performance in %SP

    Overview of %SP

    7hen the user requests a KSP page for the first tie$ A KSP converts into servlet java source

    file and copiles into servlet class file that is called as translation phase$ then onwards itworks like pure servlet for all requests this is called execution3request process phase. ?ut theethod signatures are different for "oth Servlet and KSP. Servlet has init%&$ service%& anddestroy%& ethods where as KSP has jspInit%&$ OjspService%& and jsp>estroy%& ethods. KSPhas soe advantages over servlet. KSP gives good separation "etween presentation %htl&and "usiness logic. See/verview of Servletsfor ore details. Here I use KSPLs Servletinstead of Servlet to differentiate "etween "oth.

    (ote, This Section assues that reader has soe "asic knowledge of KSP.

    Use &sp'nit() method as cache

    The default echanis of a KSP #ngine is to load a KSPLs servlet in ultithreaded environent$that is the default value of page directive in KSPLs

    9Q page isTheadSafe68true8 :

    In this environent$ a KSPLs jspInit%& ethod is called only once in its life tie. Here is a trick thatyou can use to iprove perforance using jspInit%& ethod. )ou can use this ethod to cachestatic data.

    'enerally a KSP generates not only dynaic data "ut also static data. Prograers often akea istake "y creating "oth dynaic and static data fro KSP page. /"viously there is a reason tocreate dynaic data "ecause of its nature "ut there is no need to create static data every tie forevery request in KSP page.

    -or exaple$ norally you would write a KSP page like this

    33creating static data and pass it to client

    out.print%89htl:4&5

    out.print%89head:9title:Hello world93title:93head:4&5

    http://www.precisejava.com/javaperf/j2ee/Servlets.htm#Servlets101http://www.precisejava.com/javaperf/j2ee/Servlets.htm#Servlets101http://www.precisejava.com/javaperf/j2ee/Servlets.htm#Servlets101http://www.precisejava.com/javaperf/j2ee/Servlets.htm#Servlets101
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    10/97

    out.print%29"ody:4&5

    33 create the dynaic data and pass it to client here

    33creating static data again and passing it to client

    out.print%293"ody:4&5

    out.print%893htl:4&5

    Here you are generating "oth static data and dynaic data fro OjspService%& ethod. Insteadwhat you can do is

    9R char

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    11/97

    ;

    Here the static data is created in $sp%nit() method which means that it is created only once in the life time of

    &S' and it is used in $spService() method to pass the data to the client. When you send a large amount of

    static data then you can use this techni!ue to see a considerable increase in performance.

    Optimization techniques in &spService() method

    7hen you use iplicit out o"ject to pass the data to the client fro KSP$ the KSP#ngine3container creates a KSP7riter o"ject and put it in the OjspService%& ethod. )ou donLtneed to "other a"out writing OjspService%& ethod in your KSP$ KSP #ngine does that work foryou. )ou can iprove perforance "y using the following techniques.

    +. se String?uffer rather than using B operator when you concatenate ultiple strings

    . se print%& ethod instead of println%& ethod of out%iplicit& o"ject

    C. se Servlet/utputStrea instead of KSP7riter

    D. Initiali@e outwith proper si@e in the page directive

    E. -lush the data partly

    F. *inii@e the aount of code in the synchroni@ed "lock

    G. Set the content length

    +. se String?uffer for concatenation rather than using B operator. See !oncatenating Stringsfor detailed inforation.

    . println%& ethod internally calls print%& ethod and there is no need for a new line separationwhen generating htl pages. So a sall overhead of calling one ore ethod is reduced ifyou use print%& ethod directly.

    C. There is a sall overhead involved in KSP7riter "ecause it is eant for character outputstrea and it encodes data to "ytes$ rather you can directly use Servlet/utputStreawhenever you want to send "inary data.

    D. Initiali@e the outo"ject with proper si@e in the page directive. It is discussed in detail in laterpart of this section.

    E. If you want to pass huge data to the client fro your servlet$ user ay need to wait till theServlet/utputStrea or KSP7riter flushes the data. This happens generally whenever youhave a nu"er of gifs per page and you want to pass it to the client. The "etter approach is toflush the data partly using f lush%& ethod rather than flushing whole data at a tie. )ou caninitially flush header$ then navigation "ar$ then "ody content and finally footer so that the userneed not wait for whole data and he sees the header data iediately and so on withnavigation "ar$ "ody content and footer.

    out.write%header&5

    out.flush%&5 33 flush the header

    out.write%nav"ar&5

    out.flush%&5 33 flush the navigation "ar

    33 write dynaic data here

    http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm#Strings104http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm#Strings104
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    12/97

    out.flush%&5 33 flush the dynaic data

    out.write%footer&5

    out.flush%&5 33 finally flush the footer

    F. *inii@e the aount of code in the synchroni@ed "lock that is used in the service ethodwhenever you want the data to "e thread safe.

    for exaple$ you ay write like this

    synchroni@ed%this&1

    code line+5

    code line5

    code lineC5

    code lineD5

    ;

    "ut here if you want only to synchroni@e the data in the code line instead of all the lines$the"etter way is

    code line+5

    synchroni@ed%this&1code line5;

    code lineC5

    code lineD5

    This reduces the overhead of locking all the code lines.

    G. 7henever the client$ such as a "rowser requests a page it esta"lishes socket connectioninternally with the we" server to get the requested content. !lient gets the page data withultiple connections depending on si@e of the data. If the data is ore$ such as with ultiplegifs then it needs to esta"lish connection for ultiple ties to get the data. The nu"er ofconnections esta"lished will depend on default content length of the header$ and si@e of thecontent to "e traversed fro we" server to the client. ?y increasing content length$ you canreduce traffic and increase the perforance. Here is a saple of what you can do

    response.set!ontentength%int contentSi@e&5

    This ethod sets the length of the content so that the server can send data to the client "yusing !ontentJength header.

    Optimization techniques in &spestroy() method

    The jsp>estroy%& ethod is called only once in KSPLs servlet life tie$ when the KSP #nginereoves the KSPLs servlet fro eory. It is always "etter to reove instance varia"leresources such as K>?! connections$ sockets$ other physical resources in this ethod toavoid eory leaks.

    Optimization techniques in page directive

    Page directive defines attri"utes that apply to an entire KSP page. Here is an exaple of pagedirective.

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    13/97

    9Q page session68truefalse8 "uffer68none*"si@e in k"8 :

    "old values are default values. Here I have shown only a few attri"utes$ these attri"utes havean ipact on the perforance so we will discuss a"out the here.

    ?y default KSP #ngine creates session o"ject. If you donLt want to use "uilt in HttpSession fora KSP$ then ake session attri"ute value as false. It avoids unnecessary creation of session

    %iplicit& o"ject$ reduces overhead on eory and gar"age collector and increasesperforance.

    ?y default the si@e of out%iplicit o"ject of KSP7riter& o"ject is k". )ou can increase the si@eif you are sending a large aount of data.

    so set 9Q page session68false8 "uffer68+,*"8 :

    Here you need to set the si@e as per page response data if it crosses k".

    Choosing the right include mechanism

    There are two include echaniss availa"le to insert a file in a KSP page. They are

    +. include directive 9Q include file68child.jsp8 :

    . include action 9jsp,include page68child.jsp8 flush68true8 3:

    The include directive includes the content of the file during the translation phase where asinclude action includes the content of the file during execution3request processing phase.

    -or include directive$ KSP #ngine adds the content of the inserted page at translation phase$so it does not have an ipact on perforance.

    -or include action$ KSP #ngine adds the content of the inserted page at run tie whichiposes extra overhead.

    Choosing the right scope in 'useBean'action

    7hen you want to create a "ean using useBeanaction tag you can set scope for that "ean

    9jsp,use?ean id68o"ject(ae8 scope68pagerequestsessionapplication8 3:

    default value is LpageL for any "ean if you donLt specify the scope explicitly.

    ?y defining scope attri"ute$ you are defining the life tie of that o"ject$ when it has to "ecreated and when its life tie ends. To "e precise$ you are defining the availa"ility of thato"ject to a page$ request$ session %that is across ultiple requests to a user& or application%across ultiple users &. Here the scope effects the perforance if you donLt specify exactscope as per your requireent. 7hat will happen if you set a session scope for an o"jectwhich is needed only a request The o"ject will unnecessary reside in the eory even afteryour work is done. 7hen using the session or application scope o"ject you have to explicitly

    reove it after you are done. /therwise the session o"ject will "e there in the eory till youexplicitly reove the o"ject or your server reoves it after a configured tie liit % typically itis CM inutes&. It reduces the perforance "y iposing overhead on eory and gar"agecollector. The sae is the pro"le with the application scope o"jects.

    So set exact scope for an o"ject and also reove those scope o"jects iediately wheneveryou are done with the.

    Choosing the custom tags versus non custom tags

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    14/97

    !usto tags in KSP gives you reusa"ility and siplicity. Siplicity eans that you need notwrite java code in KSP rather you write custo tags for that. 0eusa"ility eans that once youwrite a piece of code as custo tag handler$ you can use this tag handler in any KSP.

    ?ut what will happen if you write a tag handler that is not reused often and is not siple Insuch cases it is "etter not to use custo tags since you need to use classes$ interfaces of

    javax.servlet.jsp.tagext$ deployent descriptor file and also you need to override ethods of

    those classes and interfaces in order to write a tag handler. KSP #ngine has to look atdescriptor file to figure out tag handler class and execute that handler. All these operations donot coe for free. It reduces perforance and it is proportional to the nu"er of tag handlersyou use in KSP. So donLt use custo tags unless you are sure of its reusa"ility.

    Cache the static and dynamic data

    The use of caching in different areas of your application gives very good perforance.'enerally every applicationLs data"ase schea will have at least soe read only ta"les. Thereis no need of accessing these ta"les every tie. )ou can cache that data in eory andreuse it instead of accessing data"ase every tie. It reduces network traffic$ consues less!P cycles and gives good perforance.

    !aching can "e done in three flavors naely static data caching$ sei dynaic data caching

    and dynaic caching. Static data eans that it doesnLt change the content in its life tie$ it isalways constant. Sei dynaic data eans that data changes "ut not very often. -orexaple the data that changes after every one hour can "e called as sei dynaic data "ut itdoes not change the data for every request. >ynaic data eans that it changes often. /ftenpeople use the word dynaic data for sei dynaic data as well so even I followed the saeterinology. In this section$ dynaic data synonyous with sei dynaic data.

    It is "est to cache static data and dynaic data in order to iprove perforance.7e willdiscuss here a"out few caching techniques to iprove KSP perforance. They are

    +. !aching static and dynaic data

    . tili@ing application server !aching facilities

    C. tili@ing KSP "uilt in facility$ sessionand application%iplicit& o"jects

    D. tili@ing third party !aching algoriths

    As we saw a"ove$ !aching at jspInit%& ethod is useful for caching static data and it reducesthe creation tie of static data. ?y writing your own algoriths for caching dynaic data$ youcan aintain dynaic caching for your application.

    )our application server ay support caching facility for dynaic data caching. -or exaple$we"logic server is giving soe custo tags for dynaic caching facility. you can use thatfacility. ook at your server docuentation for ore inforation.

    )ou can use KSPLs "uilt in facility$ sessionand applicationo"jects for caching. sessiono"jectis availa"le for a user session across ultiple requests and applicationo"ject is availa"le forall users using the application. )ou can cache data into these o"jects and get this cached datawhenever you require. The ethods that support caching are.

    session.setAttri"ute%String nae$ /"ject cachea"le/"ject&5

    session.getAttri"ute%String nae&5

    application.setAttri"ute%String nae$ /"ject cachea"le/"ject&5

    application.getAttri"ute%String nae&5

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    15/97

    )ou can even use third party vendors or open source caching algoriths to achieve caching./ne of the good open source ishttp,33www.opensyphony.co.They are offering custocaching tags for free$ they are

    9cache:93cache:

    9usecached:93usecached:

    9flush3:

    These ready ade tags are used "y sessionand applicationscope o"jects internally. )ou canset cachea"le o"ject "y key and get those o"jects using those keys$ scope % either sessionorapplication&$ tie for refreshing cachea"le o"jects$ and flushing. See this linkhttp,33www.opensyphony.co3oscache3for detailed inforation a"out these tags.

    Any of these caching techniques gives good perforance with soe liited scope and youneed to utili@e depending on your applicationLs requireent.

    Choosing the right session mechanism

    7e use session echanis to aintain client state across ultiple pages. The session startswhen the client$ such as "rowser requests for a 0 to the we" server and it ends when the

    we" server ends the session or we" server ties out the session or user logs out or usercloses the "rowser.

    There are few approaches availa"le to aintain session$ those are using

    +. session%iplicit& o"ject availa"le for any KSP % this is HttpSession provided "y servlet API&

    . Hidden fields

    C. !ookies

    D. 0 rewriting

    E. Persistent echanis

    /"viously it is difficult to select one echanis out of a"ove entioned approaches to

    aintain session data. #ach one has an ipact on perforance depending on aount of thedata to "e stored as session data and nu"er of concurrent users.

    The following ta"le gives you an idea of perforance a"out each approach.

    Session mechanism Performance escription

    session goodThere is no liit on si@e ofkeeping session data

    Hidden fields oderateThere is no liit on si@e ofpassing session data

    !ookies oderate There is a liit for cookie si@e

    0 rewriting oderate

    There is a liit for 0

    rewriting

    Persistent echanis oderate to poorThere is no liit of keepingsession data

    Here the Persistent echanis eans that you store the session data in the data"ase$ filestorage or any other persistent storage. There are a few approaches for this echanis$ theyare

    +. sing your application serverLs persistent echanis for session data storage

    http://www.opensymphony.com/http://www.opensymphony.com/http://www.opensymphony.com/http://www.opensymphony.com/oscache/http://www.opensymphony.com/http://www.opensymphony.com/oscache/
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    16/97

    . sing your own persistent echanis "y aintaining your own data"ase schea

    If you use the first approach$ generally application server converts the session o"jects into?/? data type and stores it in the data"ase. If you use second approach$ you need to designthe schea as per your session fields and need to store the session data "y writing K>?!code for that$ this gives "etter perforance than the first approach. #ither of persistentechaniss give oderate to poor perforance than other approaches "ecause of overhead

    involved in data"ase calls through K>?! and it akes calls to data"ase on every request inorder to store that session data and finally it needs to retrieve the whole session data frodata"ase "ut it scales well upon increasing session data and concurrent users.

    0 rewriting gives oderate perforance "ecause the data has to pass "etween the clientand server for every request "ut there is a liitation on aount of data that can pass through0 rewriting. It gives oderate perforance "ecause of overhead involved on the networkfor passing data on every request.

    !ookies also give oderate perforance "ecause they need to pass the session data"etween client and server. It also has the si@e liit of Dk for each cookie.

    ike 0 rewriting and !ookies$ Hidden fields need to pass the data "etween client andserver and give oderate perforance. All these three session echaniss give oderate

    perforance and is inversely proportional to the aount of session data.nlike the a"ove entioned echaniss$ session%iplicit& o"ject echanis gives "etterperforance "ecause it stores the session data in eory and reduces overhead on network./nly session id will "e passed "etween client and server. ?ut it does not scale well up onincreasing session data and concurrent users "ecause of increase in eory overhead andalso increase in overhead on gar"age collection.

    0ee"er that choosing the session echanis out of one of the a"ove approaches not onlydepends on perforance "ut also scala"ility and security. The "est approach to aintain a"alance "etween perforance$ scala"ility and security. *ixture of session echanis andHidden fields gives "oth perforance and scala"ility. ?y putting secure data in sessionandnon secure data in hidden fields you can achieve "etter security.

    Control session

    If you decide to use session%iplicit o"ject that represents HttpSession o"ject& for yoursession tracking$ then you need to know how your application server3servlet engineipleents session echanis. )ou need to take care of the following points

    +. reove session explicitly

    . session tie out value

    C. application server3servelt engine ipleentation

    'enerally$ your application server3servlet engine will have default session tie out value as CMinutes which eans that if you donLt reove session or anipulate that session for CMinutes then your servlet engine reoves that session fro eory. If you set long sessiontie out value such as + hour$ then it keeps all the session o"jects till + hour. This approach

    effects the scala"ility and perforance "ecause of overhead on eory and gar"agecollection. In order to reduce eory overhead and to iprove perforance$ it is "etter toreove3invalidate session explicitly using session.invalidate%& ethod. And also try to adjustthe session tie out value as per your applicationLs requireent.

    Third iportant point is that your application server ay seriali@e session o"jects intopersistent echanis after crossing certain eory liit. It is expensive and reduces theperforance "ecause it not only seriali@es the single session o"ject "ut also seriali@es thetotal o"ject hierarchy. se LtransientL for varia"les to avoid unnecessary seriali@ation. See

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    17/97

    Seriali@ationfor detailed inforation. So know a"out your application server3servlet enginesession ipleentation echanis and act accordingly.

    isa"le %SP auto reloading

    *ost of the application servers3KSP engines have the capa"ility of loading KSPLs servletsdynaically$ that eans you need not restart your server whenever you change the KSP

    content. Application server3KSP engine loads the KSPLs servlet every tie when you configurethat KSPLs servlet. -or exaple$ if you configure auto reload tie as + second$ then KSPengine loads that KSPLs servlet after every + second. This feature is good at developent tie"ecause it reduces the developent tie "y avoiding restart of the server after every changein KSP. ?ut it gives poor perforance in the production due unnecessary loading and "urdenon class loader. So turn off your auto reloading feature in the configuration file to iproveperforance.

    Control #hread pool

    KSP engine creates a separate thread for every request and assigns that thread toOjspService%& ethod in its ultithreaded KSPLs servlet and finally it reoves that thread aftercopletion of OjspService%& ethod execution. It happens for every request. )our KSP engineay create a new thread for every request "y default. This default "ehavior reduces

    perforance "ecause creating and reoving threads is expensive. This can "e avoided "yusing the thread pool. KSP engine creates pool of threads at start up and assigns a threadfro pool to every request instead of creating a fresh thread every tie and it returns thatthread to the pool after copletion. KSP engine creates the thread pool with soe default si@edepending upon configuration paraeters of the configuration file for that pool. The pool willhave iniu and axiu nu"er of threads and you can configure these nu"ers in theconfiguration file of your KSP engine. The nu"er of axiu and iniu threads in pooldepend on concurrent users for your application. )ou have to estiate nu"er of concurrentusers for your application and give the thread pool si@e "ased on that. /"viously there is aliit on thread pool which depends upon your hard ware resources. ?y setting thread poolsi@e correctly$ The perforance of KSP increases significantly. )our application server3 KSPengine ay not give the facility to configure thread pool. TocatLs KSP #ngine gives thefacility to configure thread pool. ook at your application server 3 KSP engine docuentationfor the inforation a"out thread pool.

    $ey Points

    +. se jspInit%& ethod to cache static data. se String?uffer rather than using B operator when you concatenate ultiple stringsC. se print%& ethod rather than println%& ethodD. se Servlet/utputStrea instead of KSP7riter to send "inary dataE. Initiali@e the LoutL o"ject %iplicit o"ject& with proper si@e in the page directive.F. -lush the data partlyG. *inii@e code in the synchroni@ed "lock. Set the content length

    N. 0elease resources in jsp>estroy%& ethod.+M. 'ive LfalseL value to the session in the page directive to avoid session o"ject creation.++. se include directive instead of include action when you want to include the child page

    content in the translation phase.+. Avoid giving unnecessary scope in the Luse?eanL action.+C. >o not use custo tags if you do not have reusa"ility.+D. se application server caching facility+E. se *ixed session echaniss such as LsessionL with hidden fields+F. se LsessionL and LapplicationL as cache.+G. se caching tags provided "y different organi@ations like openSyphony.co

    http://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2se/Serialization.htm
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    18/97

    +. 0eove LsessionL o"jects explicitly in your progra whenever you finish the task+N. 0educe session tie out value as uch as possi"leM. se LtransientL varia"les to reduce seriali@ation overhead if your session tracking

    echanis uses seriali@ation process.+. >isa"le KSP auto reloading feature.

    . se thread pool for your KSP engine and define the si@e of thread pool as per applicationrequireent.

    Overview of -%B

    #nterprise Kava ?ean is a coponent that siplifies the jo" of developer "y providing thefollowing "uiltJin services

    +. 0*I30*IJII/P % >istri"uted coputing&

    . Transactions

    C. Security

    D. 0esource pooling E. Thread safe

    F. !lient state

    G. Persistence

    . *essaging

    N. ife cycle etc.

    As a developer$ you need not write infrastructure code for these services$ rather vendorsprovide #K? container3server that support all these services. )ou siply use these serviceswithout writing any code for the. ?ut all these services do not coe for free $ they areexpensive and coe with a price. So "efore writing an application you need to carefully look

    into all the aspects for optiu use of your resources and calculate the tradeoffs involved.

    This section focuses on how to iprove perforance when using the following types of #K?s.

    +. Stateless session "ean

    . Stateful session "ean

    C. #ntity "ean

    D. *essage driven "ean

    This section focuses on #K? +.+ and #K? .M specification. Initially we will discuss coontuning practices aong soe3all types of "eans and then discuss each of the separately.

    (ote, This Section assues that reader has soe "asic knowledge of #K?s.

    Common tuning practices in -%Bs

    Here we discuss coon tuning practices aong soe3all types of enterprise java "eans.

    Choosing "etween -%B and non.-%B

    The first thing that you can question yourself is why use #K? and why not a noral java o"jectsince #K? with services such as transactions$ 0*I30*IJII/P$ security$ client stateanageent$ persistence etc are associated with a cost. If you want these services for yourapplication then #K? is the "est choice otherwise a noral java o"ject is a "etter option. And

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    19/97

    also the decision "etween the depends on how any services you want for your application$if you want only transaction anageent then you can use KTA %Kava Transaction API& ratherthan using #K? or incase you want your application to have only distri"uted coputing then0*I30*IJII/P will suffice without #K?.

    #K? is a reusa"le coponent unlike noral java o"ject that is "acked "y coponentarchitecture$ you can deploy an #K? in any #K? copliant server$ that can "e reused.

    The following figure illustrates the underlying technology a"out how a client counicateswith an #K? ,

    -igure+, !lient to #K? counication

    This figure gives a clear picture a"out how the counication "etween client and the #K? isachieved$ the overall process is expensive.

    So use java o"ject if you do not want soe3all the services that coe with an #K?$ otherwisechoose #K?.

    Choosing "etween local -%B and remote -%B

    /nce you decide to use an #K? application the first thing that you have to decide is choosing"etween local3reote #K?. #K? .M introduced the concept of local interfaces which work as

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    20/97

    local #K? without distri"uted coputing capa"ility %0*I30*IJII/P& while #K? +.+ supports onlyreote #K?s.

    0eote #K? eans that it extends reote interface so that client counicates with #K?through 0*I30*IJII/P which involves seriali@ation$ arshalling3unarshalling for everyethod call and this has costs associated which can "e avoided if the client is on the saeachine3KU*.

    So if you want to deploy your #K? client and #K? in the sae server3KU* then you donLt needthe reote #K? "ut can use the local #K? .The local #K? does not use 0*I30*IJII/P forcounication$ it "ypasses this overhead and uses passJ"yJreference as noral javaechanis and hence is faster and efficient when copared to reote #K?s.

    The following figures illustrate the difference "etween local and reote #K?s.

    -igure, 0eote #K?

    -igureC, ocal #K?

    In #K?.M$ use ocal interfaces to reduce 0*I30*IJII/P overhead.

    Optimize with pass."y.reference

    nlike #K?.M$ #K? +.+ does not support local interfaces so you have only one option that isto treat all o"jects as reote o"jects. If you want to deploy client and #K?ean on the saeachine then also you cannot avoid the overhead of the o"jects "eing treated as reote inspite of "eing local. However soe #K? servers solve this pro"le if you configure theirdeployent descriptor files. -or exaple in 7e"logic serverLs we"logicJej"Jjar.xl file has an

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    21/97

    eleent to define wether the eleent is to "e passed "y reference or "y value. That eleentis

    9ena"leJcallJ"yJreference : true93ena"leJcallJ"yJreference :

    ?y default this eleent is set to true.

    In K?oss servers the j"oss.xl file has an eleent

    9containerJinvokerJconf:

    9optii@ed:true93optii@ed:

    93containerJinvokerJconf:

    Soe vendors ay not support passJ"yJreference as default so look at your serverdocuentation for detailed inforation and configure.

    In #K?+.+$ configure the passJ"yJreference property in vendors specific deployent descriptorfile to ake #K?s as local #K?s whenever you deploy "oth client and #K?s in the saeachine3server to iprove perforance.

    /rap entity "eans with session "ean

    If you call an entity "ean reotely fro java swing$ KSP or a servlet$ you will end up with anu"er of reote network calls that increase network overhead. 7rapping entity "eans withsession "eans solves this pro"le. The "est ethod is to ake entity "eans as local #K?sand wrap with session "ean. 'enerally to accoplish a request we need to call a lot of entity"eans$ for exaple if client wants to display an order with account info then we need to callPerson#ntity?ean$ /rder#ntity?ean$ and Account#ntity?ean. Here three reote calls areinvolved$ we can iniise the nu"er of reote calls "y wrapping these three entity "eanswith an /rder*anager session "ean thus requiring only one reote call. Session "ean getsthe request and processes three calls locally and returns values in a single call. To akeentity "eans as local you can follow the a"ove entioned approach depending on the #K?version.

    The following figure illustrates this process ,-igureD, calling entity "ean directly through network

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    22/97

    -igureE, 7rap entity "ean with session "ean to reduce network calls

    So to reduce network calls and increase perforance$ wrap entity "eans with session "eans.This technique not only iproves perforance "ut also gives good declarative transactionsupport and design.

    There is a pattern availa"le for this process$ see Session -acade.

    0educe method calls with coarse granularity

    7hen you call a ethods of reote o"ject for exaple like this ,

    reote/"ject.get(ae%&5

    reote/"ject.get!ity%&5

    reote/"ject.getState%&5

    reote/"ject.getVip!ode%&5

    Here$ there are four network calls fro client to the reote o"ject. )ou can inii@e thesenetwork calls "y reducing the nu"er of ethod calls like this ,

    33 create an o"ject and fill that o"ject locally

    PersonInfo person 6 new PersonInfo%&5

    person.set(ae%8nae8&5

    person.set!ity%8Austin8&5

    person.setState%8TW8&5

    person.setVip!ode%8GGDN8&5

    reote/"ject.getPersonInfo%person&5 33 send o"ject through network

    Here$ there is only one network call instead of three network calls.

    In the first case we set attri"ute values one "y one and send the over the network .Thisapproach is called fine grained approach$this approach needs ore network calls.

    http://www.precisejava.com/javaperf/j2ee/Patterns.htm#Patterns103http://www.precisejava.com/javaperf/j2ee/Patterns.htm#Patterns103http://www.precisejava.com/javaperf/j2ee/Patterns.htm#Patterns103
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    23/97

    In the second approach we wrap all the four attri"utes in an o"ject at the client side and sendit as an o"ject rather than each attri"ute separately. This approach is known as coarsegrained approach. This approach when copared to fine grained approach needs lessnetwork calls.

    So use coarse grained approach to inii@e the nu"er of network calls there "y iprovingperforance .

    Control serialization in remote -%Bs

    7hen you decide to write your code for distri"uted 3reote o"ject you need to carefullychoose what ethod paraeters you want to send over the network$for exaple when youpass an o"ject like this ,

    reote/"ject.setPersonInfo%person&5 33 call reote o"ject "y passing o"ject

    here$ not only the PersonInfo o"ject will "e seriali@ed and sent over network "ut all the totalPersonInfo o"ject graph %varia"les and itLs super class varia"les except transient varia"les&will also "e sent through network "ecause of default "ehavior. )ou ight want to send onlyPersonInfo o"ject only "ut not total o"ject graph.

    To avoid this pro"le$ use LtransientL key word for the attri"utes that need not "e sent over thenetwork. SeeSeriali@ationsection for ore detailed inforation.

    Cache -%B!ome o"&ect references

    7hen you want to call an #K?ean fro the client$ first you need to get #K?Hoe o"jectreference through K(>I $ This is illustrated in the figurea"ove$ the code for this process isshown "elow ,

    33 get Initial!ontext

    pu"lic !ontext getInitial!ontext%& throws (aing#xception1

    Properties props6 new Properties%&5

    props.put %!ontext.P0/UI>#0O0$8urlnae8&5

    props.put%!ontext.I(ITIAO!/(T#WTO-A!T/0)$8naeservice8&5

    return new Initial!ontext%props&5

    ;

    33 get hoe reference fro K(>I

    pu"lic AccountHoe getHoe %& throws (aing#xception1

    !ontext ctx 6 setInitial!ontext%&5

    /"ject hoe6ctx.lookp%8K(>Ilookup(ae&5

    return %AccountHoe& Porta"le0eote/"ject.narrow%hoe$AccountHoe.class&5

    ;

    This code needs to "e executed each tie the client wants to call an #K?ean. This isredundant and expensive. So to solve this pro"le$ you can cache #K?Hoe o"jectreferences first tie and reuse it again and again fro cache without repeating the K(>I lookup process.

    The following code snippet shows how you can cache #K?Hoe o"ject references.

    http://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2ee/EJB.htm#EJBFigure1%23EJBFigure1http://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2ee/EJB.htm#EJBFigure1%23EJBFigure1
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    24/97

    iport javax.ej".X5

    iport javax.ri.X5

    iport java.util.X5

    iport javax.naing.X5

    pu"lic class #K?Hoe!ache 1

    33 cache hoe references in Hashta"le

    private static Hashta"le hoes 6 new Hashta"le%&5

    !ontext ctx5

    pu"lic #K?Hoe!ache%& throws (aing#xeption 1

    ;

    pu"lic static synchroni@ed #K?Hoe getHoe%!lass hoe!lass& throws (aing#xeption 1

    #K?Hoe hoe 6 %#K?Hoe& this.hoes.get%hoe!lass&5

    if%hoe 66 null& 1 ctx 6 getInitial!ontext%&5

    hoe 6 %#K?Hoe&Porta"le0eote/"ject.narrow%ctx.lookup%hoe!lass.get(ae%&&$hoe!lass&5

    this.hoes.put%hoe!lass$hoe&5

    ;

    return hoe5

    ;

    private !ontext getInitial!ontext%& throws (aing#xception 1

    Properties props6 new Properties%&5

    props.put %!ontext.P0/UI>#0O0$8urlnae8&5

    props.put%!ontext.I(ITIAO!/(T#WTO-A!T/0)$8naeservice8&5

    return new Initial!ontext%props&5

    ;

    ; 33end class

    33 client code for getting AccountHoe o"ject reference

    AccountHoe accountHoe 6

    %AccountHoeK?Hoe!ache.getHoe%AccountHoe.!lass&5Here we are getting Hoe o"ject reference the first tie and putting it in the cache andreusing it without doing expensive K(>I look up second tie onwards.There is a patternavaila"le for this technique$ see #K?Hoe-actory Pattern %Service ocator Pattern& fordetailed ipleentation.

    Control transaction

    In #K?$ )ou can use transactions either declaratively or prograatically.

    http://www.precisejava.com/javaperf/j2ee/Patterns.htm#Patterns102http://www.precisejava.com/javaperf/j2ee/Patterns.htm#Patterns102
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    25/97

    The declarative transactions in #K? are at ethod level that eans transaction starts %"egins&when ethod starts and transaction ends %coits& when ethod ends. And also transactionpropagates into the su" ethods if the parent ethod uses these su" ethods. -or exaple$if you write a session "ean ethod that calls four of the entity "ean ethods$ transactionstarts when the session ethod "egins and transaction ends when that ethod ends$ in"etween transaction propagates into four of the entity "ean ethods and gets "ack to session"ean ethod. It works like chain of transaction propagations.

    >eclarative transactions have six transaction attri"utes they are 0equired$ 0equired(ew$*andatory$ Supports$ (otSupported and (ever. )ou need to declare any of these attri"utes inej"Jjar.xl deployent descriptor file for each ethod like this.

    9ej"Jjar:

    9session:9transactionJtype:!ontainer99transactionJtype:9session:

    9asse"lyJdescriptor:

    9containerJtransaction:

    9ethod:

    9ej"Jnae:#K?(ae93ej"Jnae: 9ethodJnae:ethod(ae 3 X93ethodJnae:

    93ethod:

    9transJattri"ute:0equired93transJattri"ute:

    93containerJtransaction:

    93asse"lyJdescriptor:

    93ej"Jjar:

    )ou can give each ethod nae separately or you can give asterisk%X& for all the ethods.

    The pro"le with declarative transactions is they look innocent$ "ecause you declaretransaction attri"utes in deployent descriptor file instead of writing code for a transaction.-or exaple if you use asterisk %X&$ all ethods are involved in the transaction. 7hy do weneed a transaction for non transactional ethods it is unnecessary and takes ore tie toexecute every ethod. So you need to control transaction to avoid unnecessary transactionpropagation on every ethod. 7hat you can do is that you can divide a "eanLs ethods intotransactional ethods and non transactional ethods and assign transaction attri"utes to onlytransactional ethods$ assign L(otSupportedL or L(everL to non transactional ethods so thatyou avoid transaction propagation. ?ut note that L(otSupportedL or L(everL attri"utes canLt "eused for entity "eans "ecause entity "eans need to involve in transaction to coit data$ souse these attri"utes for session "eanLs non transactional ethods. In this process you arecontrolling transaction propagation if any ethod uses other session "eans "ut you have to "ecareful whether su" "eans need a transaction or not.

    )ou can write your own transactional code %?ean *anaged transaction& usingjavax.transaction.serTransaction interface that has ethods like "egin%&$ coit%&$ roll"ack%&etc to write transactional code.

    And one ore thing is that the transaction echanis should span for iniu tie possi"le"ecause transaction locks the data"ase data till it copletes and it does not let other clientsaccess this data.

    So control transaction "y avoiding transactions for nonJtransactional ethods.

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    26/97

    Set optimal transaction age

    If you declare a transactional attri"ute$ how long does a transaction run. If you want to akesure that your transaction should take place with in a certain tie liit$ set the transaction tieout %age& value in vendor specific deployent descriptor file. -or exaple in we"logic serverLswe"logicJej"Jjar.xl file has an eleent

    9transactionJdescriptor: 9transJtieoutJseconds:+M93transJtieoutJseconds:

    93transactionJdescriptor:

    ook at vendorLs docuentation for other severs. So set axiu transaction tie "y thisprocess to control axiu tie out of a transaction$ ake sure that the tieJout you set fortransactionis appropriate.

    Use clustering for scala"ility

    7hat happens if you deploy an #K? application and later the nu"er of clients increase$ yourhardware resources ight not "e enough to handle the increased nu"er of clients and the

    response tie ay go up thus degrading the perforance. To avoid such situations we needto go for clustering.

    !lustering is a group of servers that service the clients$ "ut the client is unaware of presenceof ultiple servers he feels that he is interacting with a single server. /nce you deploy anapplication in clustered environent$ you can increase nu"er of servers depending upon theincreasing nu"er of clients. !lustering gives good scala"ility when the nu"er of clientsincrease and also gives high availa"ility. Soe of the ajor #K? vendors support clustering.-or exaple if you deploy a cluster aware #K? application in three servers and if the firstserver is overloaded$ clients are routed autoatically to the next server depending upon theload "alancing algoriths. And also clients are routed to the other server if the first serverdies$ in this situation client state is passed to the other server to handle fro that point % this iscalled as fail over&. 7hen you deploy your application on a single server and donLt have futureanticipation of increase in nu"er of clients then do not use clustering "ecause cluster aware

    #K?eans have overheads involved.

    )ou need to configure vendor specific deployent descriptor file%or other vendor specificanner& in order to get cluster aware #K? application. 7hen you configure for clustering$ #K?!ontainer3Server generates cluster aware #K?eans. ook at vendor specific docuentationfor details on clustering. So use clustering to get high scala"ility and fail over.

    #une thread count

    )our #K? server ay have a facility to tune the nu"er of siultaneous operations3threads%thread count& it can run at a tie. If the default value of thread count provided "y your serveris less than the capa"ility of the server$ the clients requesting for an application ay "e put ina queue. >epending on your resources and the capa"ility of the server you can increase thethread count to iprove perforance. If you are not clear a"out the thread count then it is"etter to leave the default value as it is "ecause increasing thread count without sufficientresources ay degrade perforance. -or ore inforation on this see your vendordocuentation.

    Choosing "etween !ttpSession and Stateful session "ean

    ?oth ServletLs HttpSession o"ject and #K?Ls Stateful session "ean are eant to aintainclient state$ so which one is a "etter option letLs look into the advantages and disadvantagesof "oth the echaniss ,

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    27/97

    + . Stateful session "ean

    Advantages ,

    It supports transaction service $security service$ life cycle anageent$ 0*I$ instance

    cache$ thread safe etc. )ou need not write code for these services.

    It can "e used "y "oth we" "ased and non we" "ased clients %like swing etc.& . It can "e used for ultiple operations for a single http request.

    >isadvantages ,

    Since it supports a nu"er of services entioned a"ove it takes ore tie to process a

    request.

    . HttpSession o"ject

    Advantages,

    It is a siple java o"ject %perhaps a Hashta"le& and takes very less tie and resources

    to aintain a client state

    >isadvantages,

    It does not support the features discussed a"ove

    It cannot process ultiple operations for a single http request.

    So depending on your applicationLs requireent you can choose the one "est suited for you$ ifyou want the "ean only for client state anageent then HttpSession o"ject gives "etterperforance than Stateful session "ean.

    Choosing an -%B server

    7e have ore than thirty vendors who provide #K? containers3servers. So when you have tochoose a server you need to carefully look into the following issues and consider the tradeJ

    offs "etween the. The following features need to "e looked into "efore you decide on #K?server

    +. !lustering

    . oad "alancing

    C. Instance pool and instance caching

    D. a@y loading

    E. Pass "y reference for #K? +.+

    F. >ifferent locking strategies

    G. !onnection pooling

    . !ontrolling call"ack ethods such as ej"oad%&$ej"Store%& in !*P etc

    If an #K? server provides all these features then how can you ake sure a"out theperforance of your server The answer is to use the "encharking specifications availa"lesuch as TP!J7$ Q?ench etc and test the server. ?ut the pro"le with these "ench arkingpolicies is that they test only for a specific feature of your server$ so in order to test the overallperforance of your server you can use #!perf specification released "y S( to test yourserver.

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    28/97

    #cperf "enchark specification is developed under java counity process that is eantainly for #K? server perforance testing. It provides #K? code and driver to test an #K?server vigorously. -or #!perf inforation$ have a look at the following links

    http,33java.sun.co3jee3ecperf3

    )ou will also find "enchark results of various servers at the following site.

    http,33ecperf.theserverside.co3ecperf3

    http,33www.cis.csiro.au3adsat3

    In order to choose "est #K? server$ analy@e features of different #K? servers$ test using#!perf tool kit and see availa"le "encharks % see a"ove links for already availa"le"encharks& and finally decide suita"le server for your application.

    #uning Stateless session "eans

    7e already discussed coon practices in the a"ove sections. Those practices areapplica"le for Stateless session "eans also. Here we discuss specific practices for Statelesssession "eans. In order to get clear picture of the practices$ we will initially discuss Stateless

    session "ean life cycle$ since it drives soe of the practices to iprove perforance. (otethat the life cycle of all the "eans are dissiilar.

    Stateless session "ean life cycle

    ife cycle eans when an #K?ean is created and reoved "y #K? !ontainer$ and when the!ontainer calls ethods of #K?ean. The following figure illustrates the life cycle of Statelesssession "ean.

    http://java.sun.com/j2ee/ecperf/http://ecperf.theserverside.com/ecperf/http://www.cmis.csiro.au/adsat/http://java.sun.com/j2ee/ecperf/http://ecperf.theserverside.com/ecperf/http://www.cmis.csiro.au/adsat/
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    29/97

    )ou can control life cycle "y entioning instance pool si@e in vendor specific deployentdescriptor. -or exaple we"logic serverLs we"logicJej"Jjar.xl has eleent for instance poolsi@e

    9pool:

    9axJ"eansJinJfreeJpool:+MM93axJ"eansJinJfreeJpool:

    9initialJ"eansJinJfreeJpool:EM93initialJ"eansJinJfreeJpool:

    93pool:

    and K?oss serverLs j"oss.xl has an eleent 9instanceJpool:to ention pool si@e. Seevendors docuentation for inforation for other servers. Here you can specify initial "eansand axiu "eans in pool. If you ention for exaple EM "eans in initial "eans and +MM foraxiu "eans in the pool$ the life cycle starts when the server starts up.

    7hen the server starts up$ the #K? !ontainer3Server creates EM "eans using!lass.newInstance%& ethod and puts it in the pool and it calls the following call "ack ethodsof the "ean.

    setSession!ontext%ctx& and

    ej"!reate%& ethods

    these EM "eans are ready to "e accessed "y EM clients concurrently. If the client accessesexceed EM then the !ontainer creates "eans and calls the a"ove ethods till the nu"er of"eans is equal to +MM %axiu "eans in the pool&. So at any tie the !ontainer can onlyhave a axiu of +MM "eans to serve clients. 7hat will happen if the concurrent clients areore than +MM Then the container puts clients in the queue. 7e will discuss a"out this in thenext section on how you can tune the pool si@e.

    The !ontainer reoves the "eans fro the pool if the nu"er of clients accessing "eans areless. 7hen the !ontainer reoves the "eans depending on its specific algoriths % perhaps0$ east 0ecently sed&. At this tie !ontainer calls ej"0eove%& ethod of the "ean.

    If the client calls the hoe.create%& ethod$ the !ontainer creates #K?/"ject and assigns

    existing "ean fro the pool to the the client$ at this tie client neither creates a "ean nor callsej"!reate%& ethod "ecause it is already called when it created and is put in the pool. In thesae anner$ if the client calls hoe.reove%& 3 reote.reove%& ethod$ the !ontainerreoves #K?/"ject and deassigns the "ean fro the client and puts it "ack to the pool "utdoes not reove fro the pool. In Stateless session "ean life cycle$ !lient does not havecontrol over "eanLs life cycle and "eanLs call "ack ethods$ it does not know when thecreation$ destruction and call "ack ethods occur. So In Stateless session "eans the creation$destruction and call "ack ethods depend upon the pool si@e$ clients concurrent access and!ontainer algoriths.

    As the nae iplies$ a Stateless session "ean does not aintain any state % instancevaria"les values& across ethods$ that is the reason why ej"Activate%& and ej"Passivate%&ethods do not have significance in Stateless session "ean. So the !ontainer can assigndifferent "eans fro the pool to the client for successive ethods.

    7ith this discussion$ we understand the iportance of pool si@e and when the call "ackethods are executed in Stateless session "eans. (ow let us discuss how we can tuneStateless session "eans.

    #une Stateless session "eans instance pool size

    The creation and destruction of "eans is expensive. To reduce this cost$ The #K?!ontainer3Server creates pool of "eans that depending upon vendor specific configuration$you need to give a proper value for this pool si@e to increase perforance. As we discussed

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    30/97

    a"ove$ configure pool si@e$ for exaple we"logicLs we"logicJej"Jjar.xl has an eleent9pool: and K?oss serverLs j"oss.xl has an eleent 9instanceJpool:. see your vendordocuentation for configuring your #K? server pool si@e.

    The nu"er of axiu "eans in pool ipacts perforance. If this is less$ then the !ontainerhas to put the clients in the queue when the nu"er of clients accessing is ore than theaxiu pool si@e. This degrades the perforance and clients take ore tie to execute.

    -or "est perforance$ give axiu "eans as equal to nu"er of axiu clientsaccesses.

    Use setSessionConte1t() or e&"Create() method as cache

    In Stateless session "ean life cycle$ The container invokes thesetSession!ontext%Session!ontext sc& and ej"!reate%& ethods when it creates the "eaninstance first tie and puts it in the pool and later it will "e used for the other clients till it isreoved "y the !ontainer$)ou can use these ethods to acquire resources like hoe o"jectreferences of other session or entity "eans or >ataSource references and put it in instancevaria"les. /nce you acquire these resources in these ethods you need not acquireresources for each client "ecause those resources are already acquired and availa"le./"viously these resources will "e specific to a "ean "ut not availa"le glo"ally. -or glo"al

    reuse$ it is "etter to use the technique that we discussed in !ache #K?Hoe o"jectreferences.)ou can use this technique to acquire other resources also. 0ee"er that youshould not acquire physical resources like data"ase connections in these ethods if theconcurrent clients are ore and pool si@e is ore$ it is "etter to acquire that type of resourcesin each ethod and reove the in that ethod. se setSession!ontext%Session!ontext sc&and ej"!reate%& ethods to cache "ean specific resources that are needed for other clients.

    0elease resources in e&"0emove() method

    The !ontainer calls ej"0eove%& ethod just "efore reoving a "ean fro the pool. Sowhatever resources you acquired in your "ean like those discussed a"ove ust "e released inthis ethod.

    #uning Stateful session "eans

    The coon practices that we discussed a"ove are applica"le for Stateful session "eansalso. Here we discuss a"out specific practices for Stateful session "eans. In order to get aclear picture$ we will initially discuss Stateful session "eanLs life cycle.

    Stateful session "ean life cycle

    The life cycle of Stateful and Stateless "ean is differs. The reason is$ Stateful session "eanhas to aintain state %instance varia"les values& across the ethods for a client. That eansonce a client assigns values for instance varia"les using one ethod$ those values areavaila"le for other ethods also. The following figure illustrates the life cycle of Statefulsession "ean.

    -igureG, Stateful session "ean life cycle

    http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB109%23EJB109http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB109%23EJB109http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB109%23EJB109http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB109%23EJB109http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB109%23EJB109
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    31/97

    Here you see the instance cache instead of instance pool. !ache aintains "eans that havestate %Stateful& whereas pool aintains "eans that donLt have state %Stateless&. )ou cancontrol life cycle "y descri"ing instance cache si@e in vendor specific deployent descriptorfile. -or exaple we"logicLs we"logicJej"Jjar.xl has eleent for instance cache si@e

    9statefulJsessionJcache:

    9axJ"eansJinJcache:+MM93axJ"eansJinJcache:

    93statefulJsessionJcache:

    and K?oss serverLs j"oss.xl has an eleent

    9instanceJcache:9containerJcacheJconf:

    9cacheJpolicy:

    9cacheJpolicyJconf:

    9inJcapacity:E93inJcapacity:

    9axJcapacity:+M93axJcapacity:

    93cacheJpolicyJconf:

    93cacheJpolicy:

    93containerJcacheJconf:

    93instanceJcache:

    -or detailed inforation$ look at their docuentation and for other servers look at vendors

    docuentation for instance cache configuration.

    Here you can specify iniu "eans and axiu "eans in cache. Soe vendors such aswe"logic do not support configuring iniu "eans "ut support configuring axiu "eans.So look at your vendor docuentation for detailed inforation on what your #K?!ontainer3server supports.

    Here life cycle of stateful session "ean starts when the client calls create%& ethod. 7hen thethe client calls create%& ethod$ the !ontainer creates the "ean using !lass.newInstance%&and calls

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    32/97

    setSession!ontext%ctx& and

    ej"!reate%& ethods

    and puts it in the instance cache. Then onwards$ the client is assigned to that "ean till clientcalls reove%& ethod$ thus container calls ej"0eove%& and destroys the "ean. In Statefulsession "ean$ the client controls life cycle % creation and reoval "ut not activation and

    passivation&. So when does container call ej"Activate%& and ej"Passivate%& ethods -orexaple$ if you set axiu "eans in cache as +MM "eans$ when clients are accessing a"ean concurrently$ container creates "eans till +MM %axiu "ean liit& and assigns those"eans to clients. After this liit$ if the +M+st client accesses this "ean$ !ontainer passivatessoe of the idle "eans that depending on !ontainer algoriths. Kust "efore passivating"eans$ it calls ej"Passivate%& ethod. Here passivation eans$ it stores the "eanLs state%instance varia"les values& in the secondary storage %file storage or data"ase&. Thepassivation happens through Seriali@ation. ater if the the idle client accesses the "ean again$then !ontainer activates the "ean and reassigns the passivated values to its instancevaria"les and calls ej"Activate%& ethod.

    Here what we understand is that client controls creation and destruction of "eans "ut notactivation and passivation. Activation and passivation are controlled "y !ontainer and dependon instance cache si@e.

    7ith this discussion$ we understand the iportance of instance cache si@e and when the call"ack ethods are executed in Stateful session "eans. (ow let us discuss how we can tuneStateful session "eans.

    #une Stateful session "eans instance cache size

    As discussed a"ove$ )ou control activation and passivation indirectly "y descri"ing instancecache si@e in vendor specific deployent descriptor file . Activation and passivation isexpensive "ecause of seriali@ation process. If the instance cache si@e is less and concurrentactive clients are ore than instance cache si@e then activation and passivation occur often$thus degrading perforance. So in order to increase perforance$ give optial cache si@e.

    Set optimal "ean age for Stateful session "eans

    The reoval of #K?ean instance "y the !ontainer fro the instance cache depends not onlyon when the client calls reove%& ethod "ut also on #K?ean tie out value %"ean age& thatyou can configure in the vendor specific descriptor file. If the "eans tie out value is less$ the!ontainer needs to reove and create often$which is expensive. So set optial "ean age toiniise reoval and creation process.

    Control Serialization in Stateful session "eans

    7e already discussed a"out!ontrol Seriali@ation in reote #K?sthat descri"es how youneed to control seriali@ation when you pass ethod paraeters fro client to #K?ean throughnetwork. Here we discuss a"out the seriali@ation that is specific to Stateful session "ean.

    7hen the !ontainer wants to passivate a Stateful session "ean it needs to seriali@e theinstance varia"le values and store it in the secondary storage and needs to deJseriali@e thosevalues fro storage when it activates. The Seriali@ation occurs for all instance varia"lesexcept LtransientL varia"les. If the instance varia"le has a huge o"ject graph$ you ay not wantto seriali@e total graph or all the instance varia"les. So to avoid seriali@ation for unwantedvaria"les$ use LtransientL keyword for those varia"les so that seriali@ation process will "ereduced. -or ore detailed inforation a"out seriali@ation$ See the Seriali@ationsection.

    0emove Stateful session "eans e1plicitly

    http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB108%23EJB108http://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB108%23EJB108http://www.precisejava.com/javaperf/j2se/Serialization.htmhttp://www.precisejava.com/javaperf/j2ee/EJB.htm#EJB108%23EJB108http://www.precisejava.com/javaperf/j2se/Serialization.htm
  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    33/97

    The !ontainer keeps the "ean in the instance cache till the "eanLs tie out occurs or when theclient calls reove%& ethod explicitly otherwise the container passivates the "ean if the "eanis idle for ore tie. So if the client finishes work with the "ean and does not reoveexplicitly$ the !ontainer keeps the the "ean in the instance cache or passivates the "ean. Thisprocess consues unnecessary eory. So reove the "ean explicitly fro the client usingthe reove%& ethod.

    #uning -ntity "eans

    The coon tuning practices that we discussed a"ove are applica"le for #ntity "eans also.Here we discuss specific practices for #ntity "eans. In order to get a clear picture$ we willinitially discuss #ntity "ean life cycle. Here we discuss the tuning practices for "oth !*P%!ontainer anaged persistence& and ?*P %?ean anaged persistence&. et us start withentity "ean life cycle.

    -ntity "ean life cycle

    The life cycle of #ntity "eans is a co"ination of Stateless and Stateful "ean life cycles. Thereis slight difference "etween !ontainer anaged persistence %!*P& and ?ean anaged

    persistence %?*P& entity "eanLs life cycle that is negligi"le. So here we will discuss agenerali@ed life cycle that applies to "oth.

    The following figure illustrates the life cycle of #ntity "eans.

    -igureG, #ntity session "ean life cycle

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    34/97

    Here you see "oth instance pool and instance cache. instance pool aintains entity "eanswithout state data and instance cache aintains entity "eans with state data.

    )ou can control life cycle in #ntity "eans "y entioning instance pool si@e and instance cachesi@e in vendor specific deployent descriptor. -or exaple we"logicLs we"logicJej"Jjar.xlhas eleent for instance pool si@e$

    9pool:

    9axJ"eansJinJfreeJpool:+MM93axJ"eansJinJfreeJpool:

    9initialJ"eansJinJfreeJpool:EM93initialJ"eansJinJfreeJpool:

    93pool:

    and instance cache si@e

    9entityJcache:

    9axJ"eansJinJcache:+MM93axJ"eansJinJcache:

    93entityJcache:

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    35/97

    and in K?oss$ j"oss.xl has an eleent

    9instanceJpool:to ention pool si@e.

    and for instance cache si@e

    9instanceJcache:

    9containerJcacheJconf:

    9cacheJpolicy: 9cacheJpolicyJconf:

    9inJcapacity:E93inJcapacity:

    9axJcapacity:+M93axJcapacity:

    93cacheJpolicyJconf:

    93cacheJpolicy:

    93containerJcacheJconf:

    93instanceJcache:

    If you ention EM "eans as initial "eans and +MM "eans as axiu "eans for instance pool$EM %in& and +MM%ax& for instance cache$ life cycle starts when the server starts up.

    7hen the server starts up$ -irst$ the #K? !ontainer3Server creates EM "eans using!lass.newInstance%& ethod and puts the in the pool and it calls set#ntity!ontext%& ethodon each "ean. The !ontainer can reove "eans fro the pool depending on clients accessesand idle tie of "eans in the pool. 7hen it reoves the "ean fro the pool it callsunSet#ntity!ontext%& ethod on the "ean.

    (ext$ 7hen the client calls the create%& ethod$ the !ontainer calls corresponding ej"!reate%&ethod on one of the "eans in the instance pool and creates a row in the data"ase andpopulates the values to the varia"les and puts it in the instance cache after returning priarykey. At this stage an #K?/"ject is assigned to the client that counicates to the "ean in theinstance cache. (ext$ the !ontainer calls ej"Post!reate%& ethod. At this stage$ the "ean isoved fro pool to cache and is ready to serve clients "usiness ethods.

    (ext$ 7hen the client calls the "usiness ethod$ the !ontainer calls ej"oad%& that updatesthe "eans state$ executes the "usiness ethod$ and calls ej"Store%& ethod to store the datain the data"ase. If the concurrent active clients are ore than cache si@e then the containerpassivates a "ean and calls ej"Store%&$ ej"Passivate%& ethods and puts it "ack in theinstance pool. If the idle client calls again after soe tie$ container calls ej"oad%& to getlatest data$ and calls ej"Activate%& ethod and puts it in the instance cache.

    (ext$ If the client calls reove%& ethod$ the !ontainer calls ej"0eove%& ethod thatreoves the data fro the data"ase and puts the "ean "ack in the instance pool froinstance cache.

    7ith this discussion$ we understand that

    +. !lient controls life cycle of a "ean that involves creation of data in the data"ase thusoving the "ean fro pool to the cache and reoval of data fro the data"ase thus ovingthe "ean fro cache to the pool.

    . !ontainer controls the life cycle in the pool and cache and also activation and passivationprocess in the cache.

    C. ?oth client and container control ej"oad%& and ej"Store%& ethods depending upon clientLsethod calls and !ontainer activation and passivation process.

    -inally the overall life cycle depends upon clients concurrent operations$ instance pool si@eand instance cache si@e.

    (ow let us discuss how we can tune #ntity "eans.

  • 8/12/2019 Best+Practices+to+Improve+Performance+in+Servlets

    36/97

    #une -ntity "eans instance pool size

    As per #ntity "ean life cycle discussion$ we understand that we can control creation anddestruction of "eans "y descri"ing pool si@e%in and ax& in vendor specific deployentdescriptor %or other vendor specific anner&. If this si@e is less %if your default si@e is less oryou configure a saller si@e& then the !ontainer has to put the clients in the queue when thenu"er of concurrent clients accessing % create3finder3hoe ethods& are ore than the ax

    pool si@e. And also instance cache depends up on instance pool "ecause the instance cacheneeds to get "eans fro the instance pool. So if the pool si@e is less$ It degrades theperforance and clients take ore tie to execute. -or "est perforance$ give axiu"eans in pool as equal to nu"er of axiu concurrent client accesses %create3finder3hoeethods&$ so that it reduces creation and destruction of "eans.

    )ou can configure your pool si@e in vendor specific deployent descriptor % or other vendorspecific anner&. In the a"ove #ntity "ean life cyclesection$ 7e discussed how to configurethis pool si@e in 7e"logic and K?oss servers.

    #une -ntity "eans instance cache size

    As per #ntity "ean life cycle discussion$ we understand that we can control activation and

    passivation indirectly "y descri"ing instance cache si@e in vendor specific deployentdescriptor file %or other vendor specific anner&. ook at #ntity "ean life cyclesection forconfiguring instance cache si@e in 7e"logic and K?oss servers.

    Activation and passivation are expensive. -or every activation the !ontainer calls ej"oad%& toget latest data fro the data"ase and calls ej"Activate%& ethod. -or every passivation the!ontainer calls ej"Store%& to store data in the data"ase and calls ej"Passivate%& ethod.ej"oad%& and ej"Store%& ethods counicate with the data"ase to synchroni@e the latestdata. If the concurrent active clients %when the client calls "usiness ethods& are ore thaninstance cache si@e then activation and passivation occur often thus effecting perforance.So in order to increase perforance$ give optial cache si@e. !ache si@e ust "e equal toconcurrent active clients accessing the "ean.

    (ote, The instance cache si@e and pool si@e in entity "eans are larger than session "eans.

    The "eans in the pool and cache should accoodate the entity "eans requireents likefinder ethods that return large nu"er of records and populate the data in the "eans. So "ecareful when you configure entity "ean pool si@e and cache si@e. If you are not sure a"outwhat the exact paraeters are then use default pool si@e and cache si@e.

    Use set-ntityConte1t() method as