You are on page 1of 97

Best Practices to improve performance in Servlets

Overview of Servlets Servlets represent an extension to the HTTP server. It takes http request as an input and sends 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 deal with generic and http functionality that eans you can write a Servlet in java to get http request and send a http response to the client. !lient is typically a "rowser. These interfaces are i ple ented "y Servlet #ngines. There are nu erous vendors who provide Servlet #ngines to work with Servlets$ for exa ple To cat$ we"logic$ we"shpere etc. Servlet is loaded into the e ory "y Servlet #ngine and it calls init%& ethod on first request and then onwards only service%& ethod is called for every other request "y creating a separate thread for each request and finally destroy%& ethod is called when the Servlet is re oved "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 the applications. )ou can even work with single threaded odel "y i ple enting SingleThread*odel interface where the Servlet #ngine creates a separate Servlet instance for each request. (ote+, This is "rief explanation of Servlet architecture. -or availa"le "ooks and online tutorials on Servlets. ore infor ation on Servlets$ see

(ote., This Section assu es that reader has so e "asic knowledge of Servlets.

Use init() method as cache The default echanis of a Servlet #ngine is to load a Servlet in ultithreaded enviro ent. In this environ ent$ a Servlet init%& ethod is called only once in its life ti e. )ou can i prove perfor ance using init%& ethod. )ou can use this ethod to cache static data. 'enerally a Servlet generates dyna ic data and static data. Progra ers often ake a istake "y creating "oth dyna ic and static data fro service%& ethod. /"viously there is a reason to create dyna ic data "ecause of its nature "ut there is no need to create static data every ti e for every request in service%& ethod. -or exa ple$ nor ally you would write a Servlet like this pu"lic void service%HttpServlet0equest req$ HttpServlet0espnse res& throws Servlet#xception$I/#xception 1 res.set!ontentType%2text3ht l4&5 Printwriter out 6 req.get7riter%&5 out.print%89ht l:4&5

out.print%89head:9title:Hello world93title:93head:4&5 out.print%29"ody:4&5 33 send the dyna ic data here out.print%293"ody:4&5 out.print%893ht l:4&5 ; Here you are generating "oth static data and dyna ic data. Instead you can shown "elow pu"lic class servlet extends HttpServlet 1 "yte<= header5 "yte<= nav"ar5 "yte<= footer5 "yte<= otherStatic>ata5 pu"lic void init%Servlet!onfig config& throws Servlet#xception1 33create all the static data here String?uffer s" 6 new String?uffer%&5 33 "etter to initiali@e the String?uffer with so e si@e to i prove perfor ance s".append%89ht l:4&5 s".append%89head:9title:Hello world93title:93head:4&5 s".append%29"ody:4&5 header = sb.toString().getBytes(); 33 do sa e for nav"ar if its data is static 33 do sa e for footer if its data is static ; pu"lic void service%HttpServlet0equest req$ HttpServlet0esponse res& throws Servlet#xception$ I/#xception 1 res.set!ontentType%8text3ht l8&5 odify the code as

Servlet/utputStrea out.write%header&5 out.write%nav"ar&5

out 6 res.get/utputStrea %&5

33 write dyna ic 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 of Servlet 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%& following techniques. ethod for your Servlet$ you can i prove perfor ance "y using

+. Ase String?uffer rather than using B operator when you concatenate .. Ase print%& ethod instead of println%& ethod

ultiple strings

C. Ase Servlet/utputStrea

instead of Print7riter

D. Initiali@e the Print7riter with proper si@e E. -lush the data partly F. *ini i@e the a ount of code in the synchroni@ed "lock G. Set the content length

+. Ase String?uffer for concatenation rather than using B operator when you concatenate ultiple strings. See Concatenating Strings for detailed infor ation. .. println%& ethod internally calls print%& ethod and there is no need for new line separation when generating ht l pages. So a s all overhead of calling one ore ethod is reduced if you use print%& ethod directly. C. There is a s all overhead involved in Print7riter "ecause it is eant for character output strea and it encodes data to "ytes$ rather you can directly use Servlet/utputStrea whenever you want to send "inary data. D. The "etter way of creating Print7riter is ?yteArray/utputStrea "yteArray 6 new ?yteArray/utputStrea %+..HH&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 till the Servlet/utputStrea or Print7riter flushes the data. This happens generally whenever

you have a nu "er of gifs per page that you want to pass to the client. The "etter approach is to flush the data partly using flush%& ethod rather than flushing whole data at a ti e. )ou can initially flush header$ then navigation "ar$ then "ody content and finally footer so that the user need not wait for whole data and he sees the header data i ediately and so on with navigation "ar$ "ody content and footer. Servlet/utputStrea 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 dyna ic data here out.flush%&5 33 flush the dyna ic data out.write%footer&5 out.flush%&5 33 finally flush the footer out 6 res.get/utputStrea %&5

F. *ini i@e the a ount of code in the synchroni@ed "lock that is used in the service whenever you want to the data to "e thread safe. for exa ple$ you synchroni@ed%this&1 code line+5 code line.5 code lineC5 code lineD5 ; ay write like this

ethod

?ut here you ight want to synchroni@e the data in the code line. instead of all the lines so the "etter way is code line+5 synchroni@ed%this&1code line.5; 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 connection internally with the we" server to get the requested content. !lient gets the page data with ultiple connections depending on the si@e of the data. If the data is ore$ such as with

ultiple gifs then it needs to esta"lish ultiple connection to get the data. The nu "er of connections esta"lished will depend upon default content length of the header$ and si@e of the content to "e traversed fro we" server to the client. ?y increasing content length$ you can reduce traffic and increase the perfor ance. Here is an exa ple response.set!ontentIength%int contentSi@e&5 This ethod sets the length of the content that the server can send to client "y using !ontentJ Iength header. Optimization techniques in destroy() method The destroy%& ethod is called only once in its servlet life ti e when the Servlet #ngine re oves fro e ory. It is always "etter to re ove instance varia"le resources such as K>?! connections$ sockets and other physical resources in this ethod. to avoid e ory leaks.

Cache the static and dynamic data The use of caching in different areas of your application gives very good perfor ance. 'enerally every applicationLs data"ase sche a will have at least so e read only ta"les. There is no need of accessing these ta"les every ti e. )ou can cache that data in e ory and reuse it instead of accessing data"ase every ti e. It reduces network traffic$ consu es less !PA cycles and gives good perfor ance. !aching can "e done in three flavors na ely static data caching$ se i dyna ic data caching and dyna ic caching. Static data eans that the data doesnLt change in its life ti e$ it always constant. Se i dyna ic data eans that the data changes "ut not often. -or exa ple the data that changes after every one hour can "e called as se i dyna ic data$ the data does not change for every request. >yna ic data eans that it changes the data for every request. /ften people use the word dyna ic data for se i dyna ic data as well. So even I followed the sa e ter inology. In this section$ dyna ic data is synony ous with se i dyna ic data. It is "est to cache static data and dyna ic data in order to i prove perfor ance. 7e will discuss a few caching techniques to i prove Servlet perfor ance. They are as follows +. Atili@ing ?rowser caching .. !aching dyna ic data at the server C. Atili@ing application server caching facilities D. Atili@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 the creation ti e of static data for every request "ut any way finally we are passing data to the client on every request. This type of caching is useful when you want to pass "oth static data and dyna ic data to the client. /ne ore caching technique is utili@ing the "rowser cache and also cache the content at the server$ this can "e done "y avoiding a call to service%& ethod if the output content is not changed. This technique is achieved "y i ple enting getIast*odified%& ethod of HttpServlet class. 7e" servers send the response with a LIastJ*odifiedL header which tells the client when the page was last changed. 7e" "rowser sends a request with LIfJ*odifiedJSinceL header which tells we" server when it last downloaded the page. 7ith this co unication server can predict whether the file has changed or not$ if not it sends response with L(ot *odifiedLJCMD status code so that the "rowser uses its cache page instead of downloading fresh page. In order to take advantage of this technique$ Servlet should i ple ent the getIast*odified%& ethod to tell the servlet engine a"out last odified ti e. This ethod returns ti e in illiseconds.

-or i ple entation of this technique. See$ http,33www.servlets.co 3soap"ox3freecache.ht l The third technique is that your application server ay support caching facility for dyna ic data. All you need to do is that configure the caching properties file which is supported "y your server. )ou can give what Servlet you need to cache and session ti e out value to re ove cache content. -or exa ple 7e"sphere application server supports this type of facility. Have a look at this link http,33wwwJ D.i" .co 3software3we"servers3appserv3doc3vCE3ae3infocenter3was3MFMFMMMDM+.ht l The fourth technique is that you can use Servlet APILs HttpSession and Servlet!ontext o"jects for caching. HttpSession o"ject is availa"le for a user session across ultiple requests and Servlet!ontext o"ject is availa"le for all the users using the application. )ou can set cachea"le o"jects into these o"jects and get those o"jects whenever you require within their scope. The ethods that support caching are, Servlet!ontext.setAttri"ute%String na e$ /"ject cachea"le/"ject&5 Servlet!ontext.getAttri"ute%String na e&5 HttpSession.setAttri"ute%String na e$ /"ject cachea"le/"ject&5 HttpSession.getAttri"ute%String na e&5 Choosing the right session mechanism 7e use session echanis to aintain client state across ultiple pages. The session starts when the client$ such as "rowser requests for a A0I fro the we" server and it ends when the we" server ends the session or we" server ti es out the session or user logs out or user closes the "rowser. There are few approaches availa"le to +. HttpSession provided "y servlet API .. Hidden fields C. !ookies D. A0I rewriting E. Persistent echanis aintain the session$ they are using

/"viously it is difficult to select one echanis out of a"ove entioned approaches to aintain session data. #ach one i pacts perfor ance depending on a ount of the data to "e stored as session data and nu "er of concurrent users. The following ta"le gives you an idea of perfor ance "ased on the approach used. Session mechanism HttpSession Hidden fields !ookies A0I rewriting Performance good oderate oderate oderate escription There is no li it on si@e of keeping session data There is no li it on si@e of passing session data There is a li it for cookie si@e There is a li it for A0I rewriting

Persistent

echanis

oderate to poor

There is no li it of keeping session data

Here the Persistent echanis eans that you store the session data in the data"ase$ file storage or any other persistent storage. There are few a approaches for this echanis $ they are +. Asing your application serverLs persistent .. Asing your own persistent echanis "y echanis for session data storage

aintaining your own data"ase sche a

If you use the first approach$ generally application server converts the session o"jects into ?I/? data type and stores in the data"ase. If you use second approach$ you need to design the sche a as per your session fields and need to store the session data "y writing K>?! code for that$ this gives "etter perfor ance than the first approach "ecause conversion of session o"ject to ?I/? takes ore ti e than directly storing session data. #ither of persistent echanis s give oderate to poor perfor ance when co pared to other approaches "ecause of overhead involved in data"ase calls through K>?! and it akes calls to data"ase on every request in order to store that session data and finally it needs to retrieve the whole session data fro data"ase "ut it scales well on increasing session data and concurrent users. A0I rewriting gives oderate perfor ance "ecause the data has to pass "etween the client and server for every request "ut there is a li itation on a ount of data that can "e passed through A0I rewriting. It gives oderate perfor ance "ecause of overhead involved in network for passing data on every request. !ookies also give oderate perfor ance "ecause they need to pass the session data "etween client and server. It also has the si@e li it of Dk for each cookie. Iike A0I rewriting and !ookies$ Hidden fields need to pass the data "etween client and server. All these three session echanis s give oderate perfor ance and is inversely proportional to the a ount of session data. HttpSession echanis s gives "etter perfor ance when co pared to other echani s "ecause it stores the session data in e ory and reduces overhead on network. /nly session id will "e passed "etween client and the server. ?ut it does not scale well when the session data is huge and the concurrent nu "er of users are ore "ecause of increase in e ory overhead and also increase in overhead on gar"age collection. 0e e "er that choosing the session echanis fro one of the a"ove approaches is not only depends on perfor ance$ scala"ility and security. The "est approach is to aintain a "alance "etween perfor ance$ security and scala"ility "y choosing a ixed approache. *ixture of HttpSession echanis and Hidden fields gives "oth perfor ance 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 i ple ents HttpSession echanis . )ou need to take care of the following points. +. 0e ove session explicitly .. Set Session ti e out value C. Application server3servelt engine i ple entation 'enerally$ your application server3servlet engine will have default session ti e out value as CM inutes which eans that if you donLt re ove session or anipulate that session for CM

inutes then your servlet engine re oves that session fro e ory. If you set long session ti e out value such as + hour$ then it keeps all the session o"jects till + hour. This approach effects scala"ility and perfor ance "ecause of overhead on e ory and gar"age collection. In order to reduce e ory overhead and to increase perfor ance$ it is "etter to re ove3invalidate session explicitly using HttpSession.invalidate%& ethod. and also try to reduce the session ti e out value as per your applicationLs require ent. Third i portant point is that your application server ay seriali@e session o"jects after crossing certain e ory li it$ It is expensive and effects perfor ance "ecause it not only seriali@es the single session o"ject "ut also seriali@es the total o"ject hierarchy. Ase LtransientL for varia"les to avoid unnecessary seriali@ation. see Seriali@ation for detailed infor ation to i prove perfor ance. So know a"out your application server3servlet engine session i ple entation echanis and act accordingly. isa"le Servlet auto reloading *ost of the application servers3servlet engines have the capa"ility of loading servlets dyna ically$ that eans you need not restart your server whenever you change the servlet content. Application server3servlet engine loads the servlet with auto reload each ti e when you configure the servlet. -or exa ple$ if you configure auto reload as + second$ then servlet engine loads that servlet after every + second. This feature is good at develop ent ti e "ecause it reduces the develop ent ti e "y avoiding restarting the server after every change in servlet. ?ut it gives poor perfor ance at production "y unnecessary servlet loading and "urden on class loader. So turn off your auto reloading feature in the configuration file to i prove perfor ance. 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 re oves that thread after co pletion of service%& ethod execution. It happens for every request. )our servlet engine ay create a new thread for every request "y default. This default "ehavior reduces perfor ance "ecause creating and re oving 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 every request instead of creating a fresh thread every ti e and it returns that thread to the pool after co pletion. The si@e of the thread pool depends upon configuration para eters of the pool. The pool will have ini u and axi u nu "er of threads and you can configure these nu "ers in the configuration file of your servlet engine. The nu "er of axi u and ini u threads in pool depend upon concurrent users for your application. )ou have to esti ate nu "er of concurrent users for your application and give the thread pool si@e "ased on that. /"viously there is a li it on thread pool which depends on your hardware resources. ?y setting thread pool si@e correctly$ The perfor ance of servlet i proves significantly. )our application server3 KSP engine ay not have facility to configure thread pool. To catLs Servlet #ngine has the facility to configure thread pool. Iook at your application server 3 servlet engine docu entation for infor ation a"out thread pool.

$ey Points +. Ase init%& ethod to cache static data .. Ase String?uffer rather than using B operator when you concatenate C. Ase print%& ethod rather than println%& ethod D. Ase Servlet/utputStrea rather than Print7riter to send "inary data E. Initiali@e the Print7riter with proper si@e F. -lush the data partly G. *ini i@e code in the synchroni@ed "lock H. Set the content length N. 0elease resources in destroy%& ethod.

ultiple strings

+M. ++. +.. +C. +D. +E.

I ple ent getIast*odified%& ethod to use "rowser cache and server cache Ase application server caching facility Ase *ixed session echanis s such as HttpSession with hidden fields 0e ove HttpSession o"jects explicitly in your progra whenever you finish the task 0educe session ti e out value as uch as possi"le Ase 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. Ase thread pool for your servlet engine and define the si@e as per application require ent.

Best Practices to improve Performance in %SP


Overview of %SP 7hen the user requests a KSP page for the first ti e$ A KSP converts into servlet java source file and co piles into servlet class file that is called as translation phase$ then onwards it works like pure servlet for all requests this is called execution3request process phase. ?ut the ethod signatures are different for "oth Servlet and KSP. Servlet has init%&$ service%& and destroy%& ethods where as KSP has jspInit%&$ OjspService%& and jsp>estroy%& ethods. KSP has so e advantages over servlet. KSP gives good separation "etween presentation %ht l& and "usiness logic. See /verview of Servlets for ore details. Here I use KSPLs Servlet instead of Servlet to differentiate "etween "oth. (ote, This Section assu es that reader has so e "asic knowledge of KSP.

Use &sp'nit() method as cache The default echanis of a KSP #ngine is to load a KSPLs servlet in that is the default value of page directive in KSPLs 9PQ page isTheadSafe68true8 P: In this environ ent$ a KSPLs jspInit%& ethod is called only once in its life ti e. Here is a trick that you can use to i prove perfor ance using jspInit%& ethod. )ou can use this ethod to cache static data. 'enerally a KSP generates not only dyna ic data "ut also static data. Progra ers often ake a istake "y creating "oth dyna ic and static data fro KSP page. /"viously there is a reason to create dyna ic data "ecause of its nature "ut there is no need to create static data every ti e for every request in KSP page. -or exa ple$ nor ally you would write a KSP page like this 33creating static data and pass it to client out.print%89ht l:4&5 out.print%89head:9title:Hello world93title:93head:4&5 ultithreaded environ ent$

out.print%29"ody:4&5 33 create the dyna ic data and pass it to client here 33creating static data again and passing it to client out.print%293"ody:4&5 out.print%893ht l:4&5 Here you are generating "oth static data and dyna ic data fro what you can do is 9PR char<= header5 char<= nav"ar5 char<= footer5 char<= otherStatic>ata5 pu"lic void jspInit%&1 33create all the static data here String?uffer s" 6 new String?uffer%&5 33 "etter to initiali@e the String?uffer with so e si@e to i prove perfor ance s".append%89ht l:4&5 s".append%89head:9title:Hello world93title:93head:4&5 s".append%29"ody:4&5 header = sb.toString().to"har#rray(); 33 do sa e for nav"ar if its data is static 33 do sa e for footer if its data is static ; 33 end jspInit%& P: out.print%header&5 out.print%nav"ar&5 33 write dyna ic data here out.print%footer&5 ethod OjspService%& ethod. Instead

; 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 i plicit 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 donLt need to "other a"out writing OjspService%& ethod in your KSP$ KSP #ngine does that work for you. )ou can i prove perfor ance "y using the following techniques. +. Ase String?uffer rather than using B operator when you concatenate .. Ase print%& ethod instead of println%& ethod of out %i plicit& o"ject ultiple strings

C. Ase Servlet/utputStrea

instead of KSP7riter

D. Initiali@e out with proper si@e in the page directive E. -lush the data partly F. *ini i@e the a ount of code in the synchroni@ed "lock G. Set the content length +. Ase String?uffer for concatenation rather than using B operator. See !oncatenating Strings for detailed infor ation. .. println%& ethod internally calls print%& ethod and there is no need for a new line separation when generating ht l pages. So a s all overhead of calling one ore ethod is reduced if you use print%& ethod directly. C. There is a s all overhead involved in KSP7riter "ecause it is eant for character output strea and it encodes data to "ytes$ rather you can directly use Servlet/utputStrea whenever you want to send "inary data. D. Initiali@e the out o"ject with proper si@e in the page directive. It is discussed in detail in later part of this section. E. If you want to pass huge data to the client fro your servlet$ user ay need to wait till the Servlet/utputStrea or KSP7riter flushes the data. This happens generally whenever you have a nu "er of gifs per page and you want to pass it to the client. The "etter approach is to flush the data partly using flush%& ethod rather than flushing whole data at a ti e. )ou can initially flush header$ then navigation "ar$ then "ody content and finally footer so that the user need not wait for whole data and he sees the header data i ediately and so on with navigation "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 dyna ic data here

out.flush%&5 33 flush the dyna ic data out.write%footer&5 out.flush%&5 33 finally flush the footer

F. *ini i@e the a ount of code in the synchroni@ed "lock that is used in the service whenever you want the data to "e thread safe. for exa ple$ you synchroni@ed%this&1 code line+5 code line.5 code lineC5 code lineD5 ; ay write like this

ethod

"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 line.5; 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 connection internally with the we" server to get the requested content. !lient gets the page data with ultiple connections depending on si@e of the data. If the data is ore$ such as with ultiple gifs then it needs to esta"lish connection for ultiple ti es to get the data. The nu "er of connections esta"lished will depend on default content length of the header$ and si@e of the content to "e traversed fro we" server to the client. ?y increasing content length$ you can reduce traffic and increase the perfor ance. Here is a sa ple of what you can do response.set!ontentIength%int contentSi@e&5 This ethod sets the length of the content so that the server can send data to the client "y using !ontentJIength header. Optimization techniques in &sp estroy() method The jsp>estroy%& ethod is called only once in KSPLs servlet life ti e$ when the KSP #ngine re oves the KSPLs servlet fro e ory. It is always "etter to re ove instance varia"le resources such as K>?! connections$ sockets$ other physical resources in this ethod to avoid e ory leaks. Optimization techniques in page directive Page directive defines attri"utes that apply to an entire KSP page. Here is an exa ple of page directive.

9PQ page session68trueSfalse8 "uffer68noneS)*"Ssi@e in k"8 P: "old values are default values. Here I have shown only a few attri"utes$ these attri"utes have an i pact on the perfor ance 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 for a KSP$ then ake session attri"ute value as false. It avoids unnecessary creation of session %i plicit& o"ject$ reduces overhead on e ory and gar"age collector and increases perfor ance. ?y default the si@e of out %i plicit o"ject of KSP7riter& o"ject is Hk". )ou can increase the si@e if you are sending a large a ount of data. so set 9PQ page session68false8 "uffer68+,*"8 P: Here you need to set the si@e as per page response data if it crosses Hk".

Choosing the right include mechanism There are two include echanis s availa"le to insert a file in a KSP page. They are

+. include directive 9PQ include file68child.jsp8 P: .. include action 9jsp,include page68child.jsp8 flush68true8 3: The include directive includes the content of the file during the translation phase where as include 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 i pact on perfor ance. -or include action$ KSP #ngine adds the content of the inserted page at run ti e which i poses extra overhead.

Choosing the right scope in 'useBean' action 7hen you want to create a "ean using useBean action tag you can set scope for that "ean 9jsp,use?ean id68o"ject(a e8 scope68pageSrequestSsessionSapplication8 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 ti e of that o"ject$ when it has to "e created and when its life ti e ends. To "e precise$ you are defining the availa"ility of that o"ject to a page$ request$ session %that is across ultiple requests to a user& or application %across ultiple users &. Here the scope effects the perfor ance if you donLt specify exact scope as per your require ent. 7hat will happen if you set a session scope for an o"ject which is needed only a requestT The o"ject will unnecessary reside in the e ory even after your work is done. 7hen using the session or application scope o"ject you have to explicitly re ove it after you are done. /therwise the session o"ject will "e there in the e ory till you explicitly re ove the o"ject or your server re oves it after a configured ti e li it % typically it is CM inutes&. It reduces the perfor ance "y i posing overhead on e ory and gar"age collector. The sa e is the pro"le with the application scope o"jects. So set exact scope for an o"ject and also re ove those scope o"jects i you are done with the . Choosing the custom tags versus non custom tags ediately whenever

!usto tags in KSP gives you reusa"ility and si plicity. Si plicity eans that you need not write java code in KSP rather you write custo tags for that. 0eusa"ility eans that once you write 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 si pleT In such cases it is "etter not to use custo tags since you need to use classes$ interfaces of javax.servlet.jsp.tagext$ deploy ent 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 at descriptor file to figure out tag handler class and execute that handler. All these operations do not co e for free. It reduces perfor ance and it is proportional to the nu "er of tag handlers you 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 perfor ance. 'enerally every applicationLs data"ase sche a will have at least so e read only ta"les. There is no need of accessing these ta"les every ti e. )ou can cache that data in e ory and reuse it instead of accessing data"ase every ti e. It reduces network traffic$ consu es less !PA cycles and gives good perfor ance. !aching can "e done in three flavors na ely static data caching$ se i dyna ic data caching and dyna ic caching. Static data eans that it doesnLt change the content in its life ti e$ it is always constant. Se i dyna ic data eans that data changes "ut not very often. -or exa ple the data that changes after every one hour can "e called as se i dyna ic data "ut it does not change the data for every request. >yna ic data eans that it changes often. /ften people use the word dyna ic data for se i dyna ic data as well so even I followed the sa e ter inology. In this section$ dyna ic data synony ous with se i dyna ic data. It is "est to cache static data and dyna ic data in order to i prove perfor ance.7e will discuss here a"out few caching techniques to i prove KSP perfor ance. They are +. !aching static and dyna ic data .. Atili@ing application server !aching facilities C. Atili@ing KSP "uilt in facility$ session and application %i plicit& o"jects D. Atili@ing third party !aching algorith s As we saw a"ove$ !aching at jspInit%& ethod is useful for caching static data and it reduces the creation ti e of static data. ?y writing your own algorith s for caching dyna ic data$ you can aintain dyna ic caching for your application. )our application server ay support caching facility for dyna ic data caching. -or exa ple$ we"logic server is giving so e custo tags for dyna ic caching facility. you can use that facility. Iook at your server docu entation for ore infor ation. )ou can use KSPLs "uilt in facility$ session and application o"jects for caching. session o"ject is availa"le for a user session across ultiple requests and application o"ject is availa"le for all users using the application. )ou can cache data into these o"jects and get this cached data whenever you require. The ethods that support caching are. session.setAttri"ute%String na e$ /"ject cachea"le/"ject&5 session.getAttri"ute%String na e&5 application.setAttri"ute%String na e$ /"ject cachea"le/"ject&5 application.getAttri"ute%String na e&5

)ou can even use third party vendors or open source caching algorith s to achieve caching. /ne of the good open source is http,33www.opensy phony.co . They are offering custo caching tags for free$ they are 9cache:93cache: 9usecached:93usecached: 9flush3: These ready ade tags are used "y session and application scope o"jects internally. )ou can set cachea"le o"ject "y key and get those o"jects using those keys$ scope % either session or application&$ ti e for refreshing cachea"le o"jects$ and flushing. See this link http,33www.opensy phony.co 3oscache3 for detailed infor ation a"out these tags. Any of these caching techniques gives good perfor ance with so e li ited scope and you need to utili@e depending on your applicationLs require ent. Choosing the right session mechanism 7e use session echanis to aintain client state across ultiple pages. The session starts when the client$ such as "rowser requests for a A0I to the we" server and it ends when the we" server ends the session or we" server ti es out the session or user logs out or user closes the "rowser. There are few approaches availa"le to aintain session$ those are using

+. session %i plicit& o"ject availa"le for any KSP % this is HttpSession provided "y servlet API& .. Hidden fields C. !ookies D. A0I 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 i pact on perfor ance depending on a ount of the data to "e stored as session data and nu "er of concurrent users. The following ta"le gives you an idea of perfor ance a"out each approach. Session mechanism session Hidden fields !ookies A0I rewriting Persistent echanis Performance good oderate oderate oderate oderate to poor escription There is no li it on si@e of keeping session data There is no li it on si@e of passing session data There is a li it for cookie si@e There is a li it for A0I rewriting There is no li it of keeping session data

Here the Persistent echanis eans that you store the session data in the data"ase$ file storage or any other persistent storage. There are a few approaches for this echanis $ they are +. Asing your application serverLs persistent echanis for session data storage

.. Asing your own persistent

echanis

"y

aintaining your own data"ase sche a

If you use the first approach$ generally application server converts the session o"jects into ?I/? data type and stores it in the data"ase. If you use second approach$ you need to design the sche a as per your session fields and need to store the session data "y writing K>?! code for that$ this gives "etter perfor ance than the first approach. #ither of persistent echanis s give oderate to poor perfor ance than other approaches "ecause of overhead involved in data"ase calls through K>?! and it akes calls to data"ase on every request in order to store that session data and finally it needs to retrieve the whole session data fro data"ase "ut it scales well upon increasing session data and concurrent users. A0I rewriting gives oderate perfor ance "ecause the data has to pass "etween the client and server for every request "ut there is a li itation on a ount of data that can pass through A0I rewriting. It gives oderate perfor ance "ecause of overhead involved on the network for passing data on every request. !ookies also give oderate perfor ance "ecause they need to pass the session data "etween client and server. It also has the si@e li it of Dk for each cookie. Iike A0I rewriting and !ookies$ Hidden fields need to pass the data "etween client and server and give oderate perfor ance. All these three session echanis s give oderate perfor ance and is inversely proportional to the a ount of session data. Anlike the a"ove entioned echanis s$ session %i plicit& o"ject echanis gives "etter perfor ance "ecause it stores the session data in e ory and reduces overhead on network. /nly session id will "e passed "etween client and server. ?ut it does not scale well up on increasing session data and concurrent users "ecause of increase in e ory overhead and also increase in overhead on gar"age collection. 0e e "er that choosing the session echanis out of one of the a"ove approaches not only depends on perfor ance "ut also scala"ility and security. The "est approach to aintain a "alance "etween perfor ance$ scala"ility and security. *ixture of session echanis and Hidden fields gives "oth perfor ance and scala"ility. ?y putting secure data in session and non secure data in hidden fields you can achieve "etter security. Control session If you decide to use session %i plicit o"ject that represents HttpSession o"ject& for your session tracking$ then you need to know how your application server3servlet engine i ple ents session echanis . )ou need to take care of the following points +. re ove session explicitly .. session ti e out value C. application server3servelt engine i ple entation 'enerally$ your application server3servlet engine will have default session ti e out value as CM inutes which eans that if you donLt re ove session or anipulate that session for CM inutes then your servlet engine re oves that session fro e ory. If you set long session ti e out value such as + hour$ then it keeps all the session o"jects till + hour. This approach effects the scala"ility and perfor ance "ecause of overhead on e ory and gar"age collection. In order to reduce e ory overhead and to i prove perfor ance$ it is "etter to re ove3invalidate session explicitly using session.invalidate%& ethod. And also try to adjust the session ti e out value as per your applicationLs require ent. Third i portant point is that your application server ay seriali@e session o"jects into persistent echanis after crossing certain e ory li it. It is expensive and reduces the perfor ance "ecause it not only seriali@es the single session o"ject "ut also seriali@es the total o"ject hierarchy. Ase LtransientL for varia"les to avoid unnecessary seriali@ation. See

Seriali@ation for detailed infor ation. So know a"out your application server3servlet engine session i ple entation echanis and act accordingly. isa"le %SP auto reloading *ost of the application servers3KSP engines have the capa"ility of loading KSPLs servlets dyna ically$ that eans you need not restart your server whenever you change the KSP content. Application server3KSP engine loads the KSPLs servlet every ti e when you configure that KSPLs servlet. -or exa ple$ if you configure auto reload ti e as + second$ then KSP engine loads that KSPLs servlet after every + second. This feature is good at develop ent ti e "ecause it reduces the develop ent ti e "y avoiding restart of the server after every change in KSP. ?ut it gives poor perfor ance in the production due unnecessary loading and "urden on class loader. So turn off your auto reloading feature in the configuration file to i prove perfor ance. Control #hread pool KSP engine creates a separate thread for every request and assigns that thread to OjspService%& ethod in its ultithreaded KSPLs servlet and finally it re oves that thread after co pletion of OjspService%& ethod execution. It happens for every request. )our KSP engine ay create a new thread for every request "y default. This default "ehavior reduces perfor ance "ecause creating and re oving threads is expensive. This can "e avoided "y using the thread pool. KSP engine creates pool of threads at start up and assigns a thread fro pool to every request instead of creating a fresh thread every ti e and it returns that thread to the pool after co pletion. KSP engine creates the thread pool with so e default si@e depending upon configuration para eters of the configuration file for that pool. The pool will have ini u and axi u nu "er of threads and you can configure these nu "ers in the configuration file of your KSP engine. The nu "er of axi u and ini u threads in pool depend on concurrent users for your application. )ou have to esti ate nu "er of concurrent users for your application and give the thread pool si@e "ased on that. /"viously there is a li it on thread pool which depends upon your hard ware resources. ?y setting thread pool si@e correctly$ The perfor ance of KSP increases significantly. )our application server3 KSP engine ay not give the facility to configure thread pool. To catLs KSP #ngine gives the facility to configure thread pool. Iook at your application server 3 KSP engine docu entation for the infor ation a"out thread pool.

$ey Points +. .. C. D. E. F. G. H. N. +M. ++. +.. +C. +D. +E. +F. +G. Ase jspInit%& ethod to cache static data Ase String?uffer rather than using B operator when you concatenate ultiple strings Ase print%& ethod rather than println%& ethod Ase Servlet/utputStrea instead of KSP7riter to send "inary data Initiali@e the LoutL o"ject %i plicit o"ject& with proper si@e in the page directive. -lush the data partly *ini i@e code in the synchroni@ed "lock Set the content length 0elease resources in jsp>estroy%& ethod. 'ive LfalseL value to the session in the page directive to avoid session o"ject creation. Ase 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. >o not use custo tags if you do not have reusa"ility. Ase application server caching facility Ase *ixed session echanis s such as LsessionL with hidden fields Ase LsessionL and LapplicationL as cache. Ase caching tags provided "y different organi@ations like openSy phony.co

+H. 0e ove LsessionL o"jects explicitly in your progra whenever you finish the task +N. 0educe session ti e out value as uch as possi"le .M. Ase LtransientL varia"les to reduce seriali@ation overhead if your session tracking echanis uses seriali@ation process. .+. >isa"le KSP auto reloading feature. ... Ase thread pool for your KSP engine and define the si@e of thread pool as per application require ent. Overview of -%B #nterprise Kava ?ean is a co ponent that si plifies the jo" of developer "y providing the following "uiltJin services +. 0*I30*IJII/P % >istri"uted co puting& .. Transactions C. Security D. 0esource pooling E. Thread safe F. !lient state G. Persistence H. *essaging N. Iife cycle etc. As a developer$ you need not write infrastructure code for these services$ rather vendors provide #K? container3server that support all these services. )ou si ply use these services without writing any code for the . ?ut all these services do not co e for free $ they are expensive and co e with a price. So "efore writing an application you need to carefully look into all the aspects for opti u use of your resources and calculate the tradeoffs involved. This section focuses on how to i prove perfor ance 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 co on tuning practices a ong so e3all types of "eans and then discuss each of the separately. (ote, This Section assu es that reader has so e "asic knowledge of #K?s. Common tuning practices in -%Bs Here we discuss co on tuning practices a ong so e3all 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 nor al java o"ject since #K? with services such as transactions$ 0*I30*IJII/P$ security$ client state anage ent$ persistence etc are associated with a cost. If you want these services for your application then #K? is the "est choice otherwise a nor al java o"ject is a "etter option. And

also the decision "etween the depends on how any services you want for your application$ if you want only transaction anage ent then you can use KTA %Kava Transaction API& rather than using #K? or incase you want your application to have only distri"uted co puting then 0*I30*IJII/P will suffice without #K?. #K? is a reusa"le co ponent unlike nor al java o"ject that is "acked "y co ponent architecture$ you can deploy an #K? in any #K? co pliant server$ that can "e reused. The following figure illustrates the underlying technology a"out how a client co with an #K? , -igure+, !lient to #K? co unication unicates

This figure gives a clear picture a"out how the co achieved$ the overall process is expensive.

unication "etween client and the #K? is

So use java o"ject if you do not want so e3all the services that co e with an #K?$ otherwise choose #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 local3re ote #K?. #K? ..M introduced the concept of local interfaces which work as

local #K? without distri"uted co puting capa"ility %0*I30*IJII/P& while #K? +.+ supports only re ote #K?s. 0e ote #K? eans that it extends re ote interface so that client co unicates with #K? through 0*I30*IJII/P which involves seriali@ation$ arshalling3un arshalling for every ethod call and this has costs associated which can "e avoided if the client is on the sa e achine3KU*. So if you want to deploy your #K? client and #K? in the sa e server3KU* then you donLt need the re ote #K? "ut can use the local #K? .The local #K? does not use 0*I30*IJII/P for co unication$ it "ypasses this overhead and uses passJ"yJreference as nor al java echanis and hence is faster and efficient when co pared to re ote #K?s. The following figures illustrate the difference "etween local and re ote #K?s. -igure., 0e ote #K?

-igureC, Iocal #K?

In #K?..M$ use Iocal interfaces to reduce 0*I30*IJII/P overhead. Optimize with pass."y.reference Anlike #K?..M$ #K? +.+ does not support local interfaces so you have only one option that is to treat all o"jects as re ote o"jects. If you want to deploy client and #K?ean on the sa e achine then also you cannot avoid the overhead of the o"jects "eing treated as re ote in spite of "eing local. However so e #K? servers solve this pro"le if you configure their deploy ent descriptor files. -or exa ple in 7e"logic serverLs we"logicJej"Jjar.x l file has an

ele ent to define wether the ele ent is to "e passed "y reference or "y value. That ele ent is 9ena"leJcallJ"yJreference : true93ena"leJcallJ"yJreference : ?y default this ele ent is set to true. In K?oss servers the j"oss.x l file has an ele ent 9containerJinvokerJconf: 9opti i@ed:true93opti i@ed: 93containerJinvokerJconf: So e vendors ay not support passJ"yJreference as default so look at your server docu entation for detailed infor ation and configure. In #K?+.+$ configure the passJ"yJreference property in vendors specific deploy ent descriptor file to ake #K?s as local #K?s whenever you deploy "oth client and #K?s in the sa e achine3server to i prove perfor ance. /rap entity "eans with session "ean If you call an entity "ean re otely fro java swing$ KSP or a servlet$ you will end up with a nu "er of re ote network calls that increase network overhead. 7rapping entity "eans with session "eans solves this pro"le . The "est ethod is to ake entity "eans as local #K?s and wrap with session "ean. 'enerally to acco plish a request we need to call a lot of entity "eans$ for exa ple if client wants to display an order with account info then we need to call Person#ntity?ean$ /rder#ntity?ean$ and Account#ntity?ean. Here three re ote calls are involved$ we can ini ise the nu "er of re ote calls "y wrapping these three entity "eans with an /rder*anager session "ean thus requiring only one re ote call. Session "ean gets the request and processes three calls locally and returns values in a single call. To ake entity "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

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

So to reduce network calls and increase perfor ance$ wrap entity "eans with session "eans. This technique not only i proves perfor ance "ut also gives good declarative transaction support 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 re ote o"ject for exa ple like this ,

re ote/"ject.get(a e%&5 re ote/"ject.get!ity%&5 re ote/"ject.getState%&5 re ote/"ject.getVip!ode%&5 Here$ there are four network calls fro client to the re ote o"ject. )ou can network 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(a e%8na e8&5 person.set!ity%8Austin8&5 person.setState%8TW8&5 person.setVip!ode%8GHGDN8&5 re ote/"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 .This approach is called fine grained approach$this approach needs ore network calls. ini i@e these

In the second approach we wrap all the four attri"utes in an o"ject at the client side and send it as an o"ject rather than each attri"ute separately. This approach is known as coarse grained approach. This approach when co pared to fine grained approach needs less network calls. So use coarse grained approach to perfor ance . ini i@e the nu "er of network calls there "y i proving

Control serialization in remote -%Bs 7hen you decide to write your code for distri"uted 3re ote o"ject you need to carefully choose what ethod para eters you want to send over the network$for exa ple when you pass an o"ject like this , re ote/"ject.setPersonInfo%person&5 33 call re ote o"ject "y passing o"ject here$ not only the PersonInfo o"ject will "e seriali@ed and sent over network "ut all the total PersonInfo 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 only PersonInfo 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 the network. See Seriali@ation section for ore detailed infor ation. Cache -%B!ome o"&ect references 7hen you want to call an #K?ean fro the client$ first you need to get #K?Ho e o"ject reference through K(>I $ This is illustrated in the figure a"ove$ the code for this process is shown "elow , 33 get Initial!ontext pu"lic !ontext getInitial!ontext%& throws (a ing#xception1 Properties props6 new Properties%&5 props.put %!ontext.P0/UI>#0OA0I$8urlna e8&5 props.put%!ontext.I(ITIAIO!/(T#WTO-A!T/0)$8na eservice8&5 return new Initial!ontext%props&5 ; 33 get ho e reference fro K(>I

pu"lic AccountHo e getHo e %& throws (a ing#xception1 !ontext ctx 6 setInitial!ontext%&5 /"ject ho e6ctx.lookAp%8K(>Ilookup(a e&5 return %AccountHo e& Porta"le0e ote/"ject.narrow%ho e$AccountHo e.class&5 ; This code needs to "e executed each ti e the client wants to call an #K?ean. This is redundant and expensive. So to solve this pro"le $ you can cache #K?Ho e o"ject references first ti e and reuse it again and again fro cache without repeating the K(>I look up process. The following code snippet shows how you can cache #K?Ho e o"ject references.

i port javax.ej".X5 i port javax.r i.X5 i port java.util.X5 i port javax.na ing.X5 pu"lic class #K?Ho e!ache 1 33 cache ho e references in Hashta"le private static Hashta"le ho es 6 new Hashta"le%&5 !ontext ctx5 pu"lic #K?Ho e!ache%& throws (a ing#xeption 1 ; pu"lic static synchroni@ed #K?Ho e getHo e%!lass ho e!lass& throws (a ing#xeption 1 #K?Ho e ho e 6 %#K?Ho e& this.ho es.get%ho e!lass&5 if%ho e 66 null& 1 ctx 6 getInitial!ontext%&5 ho e 6 %#K?Ho e& Porta"le0e ote/"ject.narrow%ctx.lookup%ho e!lass.get(a e%&&$ho e!lass&5 this.ho es.put%ho e!lass$ho e&5 ; return ho e5 ; private !ontext getInitial!ontext%& throws (a ing#xception 1 Properties props6 new Properties%&5 props.put %!ontext.P0/UI>#0OA0I$8urlna e8&5 props.put%!ontext.I(ITIAIO!/(T#WTO-A!T/0)$8na eservice8&5 return new Initial!ontext%props&5 ; ; 33end class 33 client code for getting AccountHo e o"ject reference AccountHo e accountHo e 6 %AccountHo e&#K?Ho e!ache.getHo e%AccountHo e.!lass&5 Here we are getting Ho e o"ject reference the first ti e and putting it in the cache and reusing it without doing expensive K(>I look up second ti e onwards.There is a pattern availa"le for this technique$ see #K?Ho e-actory Pattern %Service Iocator Pattern& for detailed i ple entation. Control transaction In #K?$ )ou can use transactions either declaratively or progra atically.

The declarative transactions in #K? are at ethod level that eans transaction starts %"egins& when ethod starts and transaction ends %co its& when ethod ends. And also transaction propagates into the su" ethods if the parent ethod uses these su" ethods. -or exa ple$ if you write a session "ean ethod that calls four of the entity "ean ethods$ transaction starts 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 in ej"Jjar.x l deploy ent descriptor file for each ethod like this. 9ej"Jjar: 9session:9transactionJtype:!ontainer99transactionJtype:9session: 9asse "lyJdescriptor: 9containerJtransaction: 9 ethod: 9ej"Jna e:#K?(a e93ej"Jna e: 9 ethodJna e: ethod(a e 3 X93 ethodJna e: 93 ethod: 9transJattri"ute:0equired93transJattri"ute: 93containerJtransaction: 93asse "lyJdescriptor: 93ej"Jjar: )ou can give each ethod na e separately or you can give asterisk%X& for all the ethods.

The pro"le with declarative transactions is they look innocent$ "ecause you declare transaction attri"utes in deploy ent descriptor file instead of writing code for a transaction. -or exa ple if you use asterisk %X&$ all ethods are involved in the transaction. 7hy do we need a transaction for non transactional ethodsT it is unnecessary and takes ore ti e to execute every ethod. So you need to control transaction to avoid unnecessary transaction propagation on every ethod. 7hat you can do is that you can divide a "eanLs ethods into transactional ethods and non transactional ethods and assign transaction attri"utes to only transactional ethods$ assign L(otSupportedL or L(everL to non transactional ethods so that you avoid transaction propagation. ?ut note that L(otSupportedL or L(everL attri"utes canLt "e used for entity "eans "ecause entity "eans need to involve in transaction to co it data$ so use these attri"utes for session "eanLs non transactional ethods. In this process you are controlling transaction propagation if any ethod uses other session "eans "ut you have to "e careful whether su" "eans need a transaction or not. )ou can write your own transactional code %?ean *anaged transaction& using javax.transaction.AserTransaction interface that has ethods like "egin%&$ co etc to write transactional code. it%&$ roll"ack%&

And one ore thing is that the transaction echanis should span for ini u ti e possi"le "ecause transaction locks the data"ase data till it co pletes and it does not let other clients access this data. So control transaction "y avoiding transactions for nonJtransactional ethods.

Set optimal transaction age If you declare a transactional attri"ute$ how long does a transaction runT. If you want to ake sure that your transaction should take place with in a certain ti e li it$ set the transaction ti e out %age& value in vendor specific deploy ent descriptor file. -or exa ple in we"logic serverLs we"logicJej"Jjar.x l file has an ele ent 9transactionJdescriptor: 9transJti eoutJseconds:+.M93transJti eoutJseconds: 93transactionJdescriptor: Iook at vendorLs docu entation for other severs. So set axi u transaction ti e "y this process to control axi u ti e out of a transaction$ ake sure that the ti eJout you set for transactionis appropriate. Use clustering for scala"ility 7hat happens if you deploy an #K? application and later the nu "er of clients increase$ your hardware resources ight not "e enough to handle the increased nu "er of clients and the response ti e ay go up thus degrading the perfor ance. To avoid such situations we need to go for clustering. !lustering is a group of servers that service the clients$ "ut the client is unaware of presence of ultiple servers he feels that he is interacting with a single server. /nce you deploy an application in clustered environ ent$ you can increase nu "er of servers depending upon the increasing nu "er of clients. !lustering gives good scala"ility when the nu "er of clients increase and also gives high availa"ility. So e of the ajor #K? vendors support clustering. -or exa ple if you deploy a cluster aware #K? application in three servers and if the first server is overloaded$ clients are routed auto atically to the next server depending upon the load "alancing algorith s. And also clients are routed to the other server if the first server dies$ in this situation client state is passed to the other server to handle fro that point % this is called as fail over&. 7hen you deploy your application on a single server and donLt have future anticipation 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 deploy ent descriptor file%or other vendor specific anner& in order to get cluster aware #K? application. 7hen you configure for clustering$ #K? !ontainer3Server generates cluster aware #K?eans. Iook at vendor specific docu entation for 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 si ultaneous operations3threads %thread count& it can run at a ti e. If the default value of thread count provided "y your server is less than the capa"ility of the server$ the clients requesting for an application ay "e put in a queue. >epending on your resources and the capa"ility of the server you can increase the thread count to i prove perfor ance. 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 sufficient resources ay degrade perfor ance. -or ore infor ation on this see your vendor docu entation. Choosing "etween !ttpSession and Stateful session "ean ?oth ServletLs HttpSession o"ject and #K?Ls Stateful session "ean are eant to aintain client state$ so which one is a "etter optionT letLs look into the advantages and disadvantages of "oth the echanis s ,

+ . Stateful session "ean Advantages , It supports transaction service $security service$ life cycle anage ent$ 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 >isadvantages , Since it supports a nu "er of services request. .. HttpSession o"ject Advantages, It is a si ple java o"ject %perhaps a Hashta"le& and takes very less ti e 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. entioned a"ove it takes ore ti e to process a ultiple operations for a single http request.

So depending on your applicationLs require ent you can choose the one "est suited for you$ if you want the "ean only for client state anage ent then HttpSession o"ject gives "etter perfor ance than Stateful session "ean. Choosing an -%B server 7e have ore than thirty vendors who provide #K? containers3servers. So when you have to choose 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 .. Ioad "alancing C. Instance pool and instance caching D. Ia@y loading E. Pass "y reference for #K? +.+ F. >ifferent locking strategies G. !onnection pooling H. !ontrolling call"ack ethods such as ej"Ioad%&$ej"Store%& in !*P etc

If an #K? server provides all these features then how can you ake sure a"out the perfor ance of your serverT The answer is to use the "ench arking specifications availa"le such as TP!J7$ Q?ench etc and test the server. ?ut the pro"le with these "ench arking policies is that they test only for a specific feature of your server$ so in order to test the overall perfor ance of your server you can use #!perf specification released "y SA( to test your server.

#cperf "ench ark specification is developed under java co unity process that is eant ainly for #K? server perfor ance testing. It provides #K? code and driver to test an #K? server vigorously. -or #!perf infor ation$ have a look at the following links http,33java.sun.co 3j.ee3ecperf3 )ou will also find "ench ark results of various servers at the following site. http,33ecperf.theserverside.co 3ecperf3 http,33www.c is.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 "ench arks % see a"ove links for already availa"le "ench arks& and finally decide suita"le server for your application. #uning Stateless session "eans 7e already discussed co on practices in the a"ove sections. Those practices are applica"le for Stateless session "eans also. Here we discuss specific practices for Stateless session "eans. In order to get clear picture of the practices$ we will initially discuss Stateless session "ean life cycle$ since it drives so e of the practices to i prove perfor ance. (ote that the life cycle of all the "eans are dissi ilar. Stateless session "ean life cycle Iife cycle eans when an #K?ean is created and re oved "y #K? !ontainer$ and when the !ontainer calls ethods of #K?ean. The following figure illustrates the life cycle of Stateless session "ean.

)ou can control life cycle "y entioning instance pool si@e in vendor specific deploy ent descriptor. -or exa ple we"logic serverLs we"logicJej"Jjar.x l has ele ent for instance pool si@e 9pool: 9 axJ"eansJinJfreeJpool:+MM93 axJ"eansJinJfreeJpool: 9initialJ"eansJinJfreeJpool:EM93initialJ"eansJinJfreeJpool: 93pool: and K?oss serverLs j"oss.x l has an ele ent 9instanceJpool: to ention pool si@e. See vendors docu entation for infor ation for other servers. Here you can specify initial "eans and axi u "eans in pool. If you ention for exa ple EM "eans in initial "eans and +MM for axi u "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 of the "ean. setSession!ontext%ctx& and ej"!reate%& ethods ethods

these EM "eans are ready to "e accessed "y EM clients concurrently. If the client accesses exceed EM then the !ontainer creates "eans and calls the a"ove ethods till the nu "er of "eans is equal to +MM % axi u "eans in the pool&. So at any ti e the !ontainer can only have a axi u of +MM "eans to serve clients. 7hat will happen if the concurrent clients are ore than +MMT Then the container puts clients in the queue. 7e will discuss a"out this in the next section on how you can tune the pool si@e. The !ontainer re oves the "eans fro the pool if the nu "er of clients accessing "eans are less. 7hen the !ontainer re oves the "eans depending on its specific algorith s % perhaps I0A$ Ieast 0ecently Ased&. At this ti e !ontainer calls ej"0e ove%& ethod of the "ean. If the client calls the ho e.create%& ethod$ the !ontainer creates #K?/"ject and assigns existing "ean fro the pool to the the client$ at this ti e client neither creates a "ean nor calls ej"!reate%& ethod "ecause it is already called when it created and is put in the pool. In the sa e anner$ if the client calls ho e.re ove%& 3 re ote.re ove%& ethod$ the !ontainer re oves #K?/"ject and deassigns the "ean fro the client and puts it "ack to the pool "ut does not re ove fro the pool. In Stateless session "ean life cycle$ !lient does not have control over "eanLs life cycle and "eanLs call "ack ethods$ it does not know when the creation$ 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 algorith s. As the na e i plies$ a Stateless session "ean does not aintain any state % instance varia"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 assign different "eans fro the pool to the client for successive ethods. 7ith this discussion$ we understand the i portance of pool si@e and when the call "ack ethods are executed in Stateless session "eans. (ow let us discuss how we can tune Stateless 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 perfor ance. As we discussed

a"ove$ configure pool si@e$ for exa ple we"logicLs we"logicJej"Jjar.x l has an ele ent 9pool: and K?oss serverLs j"oss.x l has an ele ent 9instanceJpool:. see your vendor docu entation for configuring your #K? server pool si@e. The nu "er of axi u "eans in pool i pacts perfor ance. If this is less$ then the !ontainer has to put the clients in the queue when the nu "er of clients accessing is ore than the axi u pool si@e. This degrades the perfor ance and clients take ore ti e to execute. -or "est perfor ance$ give axi u "eans as equal to nu "er of axi u clients accesses. Use setSessionConte1t() or e&"Create() method as cache In Stateless session "ean life cycle$ The container invokes the setSession!ontext%Session!ontext sc& and ej"!reate%& ethods when it creates the "ean instance first ti e and puts it in the pool and later it will "e used for the other clients till it is re oved "y the !ontainer$)ou can use these ethods to acquire resources like ho e o"ject references of other session or entity "eans or >ataSource references and put it in instance varia"les. /nce you acquire these resources in these ethods you need not acquire resources 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?Ho e o"ject references. )ou can use this technique to acquire other resources also. 0e e "er that you should not acquire physical resources like data"ase connections in these ethods if the concurrent clients are ore and pool si@e is ore$ it is "etter to acquire that type of resources in each ethod and re ove the in that ethod. Ase 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"0e ove%& ethod just "efore re oving a "ean fro the pool. So whatever resources you acquired in your "ean like those discussed a"ove ust "e released in this ethod. #uning Stateful session "eans The co on practices that we discussed a"ove are applica"le for Stateful session "eans also. Here we discuss a"out specific practices for Stateful session "eans. In order to get a clear 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 "ean has to aintain state %instance varia"les values& across the ethods for a client. That eans once a client assigns values for instance varia"les using one ethod$ those values are availa"le for other ethods also. The following figure illustrates the life cycle of Stateful session "ean. -igureG, Stateful session "ean life cycle

Here you see the instance cache instead of instance pool. !ache aintains "eans that have state %Stateful& whereas pool aintains "eans that donLt have state %Stateless&. )ou can control life cycle "y descri"ing instance cache si@e in vendor specific deploy ent descriptor file. -or exa ple we"logicLs we"logicJej"Jjar.x l has ele ent for instance cache si@e 9statefulJsessionJcache: 9 axJ"eansJinJcache:+MM93 axJ"eansJinJcache: 93statefulJsessionJcache: and K?oss serverLs j"oss.x l has an ele ent 9instanceJcache: 9containerJcacheJconf: 9cacheJpolicy: 9cacheJpolicyJconf: 9 inJcapacity:E93 inJcapacity: 9 axJcapacity:+M93 axJcapacity: 93cacheJpolicyJconf: 93cacheJpolicy: 93containerJcacheJconf: 93instanceJcache: -or detailed infor ation$ look at their docu entation and for other servers look at vendors docu entation for instance cache configuration. Here you can specify ini u "eans and axi u "eans in cache. So e vendors such as we"logic do not support configuring ini u "eans "ut support configuring axi u "eans. So look at your vendor docu entation for detailed infor ation on what your #K? !ontainer3server supports. Here life cycle of stateful session "ean starts when the client calls create%& ethod. 7hen the the client calls create%& ethod$ the !ontainer creates the "ean using !lass.newInstance%& and calls

setSession!ontext%ctx& and ej"!reate%& ethods

and puts it in the instance cache. Then onwards$ the client is assigned to that "ean till client calls re ove%& ethod$ thus container calls ej"0e ove%& and destroys the "ean. In Stateful session "ean$ the client controls life cycle % creation and re oval "ut not activation and passivation&. So when does container call ej"Activate%& and ej"Passivate%& ethodsT -or exa ple$ if you set axi u "eans in cache as +MM "eans$ when clients are accessing a "ean concurrently$ container creates "eans till +MM % axi u "ean li it& and assigns those "eans to clients. After this li it$ if the +M+st client accesses this "ean$ !ontainer passivates so e of the idle "eans that depending on !ontainer algorith s. 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&. The passivation happens through Seriali@ation. Iater if the the idle client accesses the "ean again$ then !ontainer activates the "ean and reassigns the passivated values to its instance varia"les and calls ej"Activate%& ethod. Here what we understand is that client controls creation and destruction of "eans "ut not activation and passivation. Activation and passivation are controlled "y !ontainer and depend on instance cache si@e. 7ith this discussion$ we understand the i portance of instance cache si@e and when the call "ack ethods are executed in Stateful session "eans. (ow let us discuss how we can tune Stateful session "eans. #une Stateful session "eans instance cache size As discussed a"ove$ )ou control activation and passivation indirectly "y descri"ing instance cache si@e in vendor specific deploy ent descriptor file . Activation and passivation is expensive "ecause of seriali@ation process. If the instance cache si@e is less and concurrent active clients are ore than instance cache si@e then activation and passivation occur often$ thus degrading perfor ance. So in order to increase perfor ance$ give opti al cache si@e. Set optimal "ean age for Stateful session "eans The re oval of #K?ean instance "y the !ontainer fro the instance cache depends not only on when the client calls re ove%& ethod "ut also on #K?ean ti e out value %"ean age& that you can configure in the vendor specific descriptor file. If the "eans ti e out value is less$ the !ontainer needs to re ove and create often$which is expensive. So set opti al "ean age to ini ise re oval and creation process. Control Serialization in Stateful session "eans 7e already discussed a"out !ontrol Seriali@ation in re ote #K?s that descri"es how you need to control seriali@ation when you pass ethod para eters fro client to #K?ean through network. 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 the instance varia"le values and store it in the secondary storage and needs to deJseriali@e those values fro storage when it activates. The Seriali@ation occurs for all instance varia"les except LtransientL varia"les. If the instance varia"le has a huge o"ject graph$ you ay not want to seriali@e total graph or all the instance varia"les. So to avoid seriali@ation for unwanted varia"les$ use LtransientL keyword for those varia"les so that seriali@ation process will "e reduced. -or ore detailed infor ation a"out seriali@ation$ See the Seriali@ation section. 0emove Stateful session "eans e1plicitly

The !ontainer keeps the "ean in the instance cache till the "eanLs ti e out occurs or when the client calls re ove%& ethod explicitly otherwise the container passivates the "ean if the "ean is idle for ore ti e. So if the client finishes work with the "ean and does not re ove explicitly$ the !ontainer keeps the the "ean in the instance cache or passivates the "ean. This process consu es unnecessary e ory. So re ove the "ean explicitly fro the client using the re ove%& ethod. #uning -ntity "eans The co on 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 will initially discuss #ntity "ean life cycle. Here we discuss the tuning practices for "oth !*P %!ontainer anaged persistence& and ?*P %?ean anaged persistence&. Iet us start with entity "ean life cycle. -ntity "ean life cycle The life cycle of #ntity "eans is a co "ination of Stateless and Stateful "ean life cycles. There is 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 a generali@ed life cycle that applies to "oth. The following figure illustrates the life cycle of #ntity "eans. -igureG, #ntity session "ean life cycle

Here you see "oth instance pool and instance cache. instance pool aintains entity "eans without 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 cache si@e in vendor specific deploy ent descriptor. -or exa ple we"logicLs we"logicJej"Jjar.x l has ele ent for instance pool si@e$ 9pool: 9 axJ"eansJinJfreeJpool:+MM93 axJ"eansJinJfreeJpool: 9initialJ"eansJinJfreeJpool:EM93initialJ"eansJinJfreeJpool: 93pool: and instance cache si@e 9entityJcache: 9 axJ"eansJinJcache:+MM93 axJ"eansJinJcache: 93entityJcache:

and in K?oss$ j"oss.x l has an ele ent 9instanceJpool: to ention pool si@e.

and for instance cache si@e 9instanceJcache: 9containerJcacheJconf: 9cacheJpolicy: 9cacheJpolicyJconf: 9 inJcapacity:E93 inJcapacity: 9 axJcapacity:+M93 axJcapacity: 93cacheJpolicyJconf: 93cacheJpolicy: 93containerJcacheJconf: 93instanceJcache: If you ention EM "eans as initial "eans and +MM "eans as axi u "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%& ethod on each "ean. The !ontainer can re ove "eans fro the pool depending on clients accesses and idle ti e of "eans in the pool. 7hen it re oves the "ean fro the pool it calls unSet#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 and populates the values to the varia"les and puts it in the instance cache after returning pri ary key. At this stage an #K?/"ject is assigned to the client that co unicates to the "ean in the instance cache. (ext$ the !ontainer calls ej"Post!reate%& ethod. At this stage$ the "ean is oved fro pool to cache and is ready to serve clients "usiness ethods. (ext$ 7hen the client calls the "usiness ethod$ the !ontainer calls ej"Ioad%& that updates the "eans state$ executes the "usiness ethod$ and calls ej"Store%& ethod to store the data in the data"ase. If the concurrent active clients are ore than cache si@e then the container passivates a "ean and calls ej"Store%&$ ej"Passivate%& ethods and puts it "ack in the instance pool. If the idle client calls again after so e ti e$ container calls ej"Ioad%& to get latest data$ and calls ej"Activate%& ethod and puts it in the instance cache. (ext$ If the client calls re ove%& ethod$ the !ontainer calls ej"0e ove%& ethod that re oves the data fro the data"ase and puts the "ean "ack in the instance pool fro instance cache. 7ith this discussion$ we understand that +. !lient controls life cycle of a "ean that involves creation of data in the data"ase thus oving the "ean fro pool to the cache and re oval of data fro the data"ase thus oving the "ean fro cache to the pool. .. !ontainer controls the life cycle in the pool and cache and also activation and passivation process in the cache. C. ?oth client and container control ej"Ioad%& and ej"Store%& ethods depending upon clientLs ethod calls and !ontainer activation and passivation process. -inally the overall life cycle depends upon clients concurrent operations$ instance pool si@e and instance cache si@e. (ow let us discuss how we can tune #ntity "eans.

#une -ntity "eans instance pool size As per #ntity "ean life cycle discussion$ we understand that we can control creation and destruction of "eans "y descri"ing pool si@e% in and ax& in vendor specific deploy ent descriptor %or other vendor specific anner&. If this si@e is less %if your default si@e is less or you configure a s aller si@e& then the !ontainer has to put the clients in the queue when the nu "er of concurrent clients accessing % create3finder3ho e ethods& are ore than the ax pool si@e. And also instance cache depends up on instance pool "ecause the instance cache needs to get "eans fro the instance pool. So if the pool si@e is less$ It degrades the perfor ance and clients take ore ti e to execute. -or "est perfor ance$ give axi u "eans in pool as equal to nu "er of axi u concurrent client accesses %create3finder3ho e ethods&$ so that it reduces creation and destruction of "eans. )ou can configure your pool si@e in vendor specific deploy ent descriptor % or other vendor specific anner&. In the a"ove #ntity "ean life cycle section$ 7e discussed how to configure this 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 deploy ent descriptor file %or other vendor specific anner&. Iook at #ntity "ean life cycle section for configuring instance cache si@e in 7e"logic and K?oss servers. Activation and passivation are expensive. -or every activation the !ontainer calls ej"Ioad%& to get 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"Ioad%& and ej"Store%& ethods co unicate with the data"ase to synchroni@e the latest data. If the concurrent active clients %when the client calls "usiness ethods& are ore than instance cache si@e then activation and passivation occur often thus effecting perfor ance. So in order to increase perfor ance$ give opti al cache si@e. !ache si@e ust "e equal to concurrent 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 acco odate the entity "eans require ents like finder ethods that return large nu "er of records and populate the data in the "eans. So "e careful when you configure entity "ean pool si@e and cache si@e. If you are not sure a"out what the exact para eters are then use default pool si@e and cache si@e. Use set-ntityConte1t() method as cache set#ntity!ontext%& is called only once in a "eanLs life ti e. ?ecause #ntity "eans in the pool are reused "y nu "er of other clients$ you can cache any "ean specific resources like #ntity ho e references and >ataSource references in this ethod. )ou need to declare those resources as instance varia"les and acquire the in this ethod. It is si ilar to the technique that we already discussed in Ase setSession!ontext%& as cache. 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?Ho e o"ject references. )ou can use this technique to acquire other resources also. 0e e "er that you should not acquire physical resources like data"ase connections in these ethods if the concurrent clients are ore and pool si@e is ore$ it is "etter to acquire such resources in each ethod and release the in that ethod only. Ase set#ntity!ontext%& ethod to cache "ean specific resources that are needed "y other clients as well. 0elease resources in unSet-ntityConte1t() method

The !ontainer calls unSet#ntity!ontext%& ethod just "efore re oving a "ean fro the pool. So whatever resources that were acquired %as we discussed a"ove& need to "e released in this ethod. Use 2azy loading 7henever you i ple ent parent child relationships +,+ %one to one&$ +,* %one to any& and *,* % any to any& in your #ntity "eans$ you need to "e careful a"out when you are loading child % su" relationship& data. -or exa ple$ in ?*P$ you would write a +,* %/rder?ean,IineIte like this pu"lic class /rder?ean i ple ents #ntity?ean 1 private long orderId5 private String order(a e5 private long lineIte Id5 33 -Y to the child ta"le IineIte s ta"le 33 child data fro IineIte s ta"le entity "eans& relationship

private !ollection lineIte s5 pu"lic void ej"Ioad%& 1

33 step+, select orderId$ order(a e and lineIte Id fro 3X step., get lineIte s "y looking up IineIte , look up IineIte

/rder ta"le

entity "ean

ho e reference through K(>I

lineIte s 6 lineIte Ho e.findIineIte s%lineIte Id&5 X3 ; pu"lic !ollection getIineIte s%&1 return lineIte s5 ; Here you are getting data for "oth parent and child %/rder?ean and IineIte & in one call in ej"Ioad%& ethod. This is called as aggressive3eager loading. Here you are getting data fro the data"ase on clientLs every "usiness ethod request or when transaction ends. ?ut client ay often "e interested in orderId and order(a e only "ut not IineIte s. -or exa ple$ if you use finder ethod to get orders$ you ight get +MM orders and +MMM lineIte s. )ou get +MMM lineIte s records unnecessarily even though the client didnLt want lineIte s. 0e e "er that ej"Ioad%& is called even when the !ontainer wants to activate a "ean$ this is an extra overhead. )ou can solve this pro"le using Ia@y loading. In Ia@y loading$ you load the child data as and when required. The a"ove exa ple can "e rewritten like this , pu"lic class /rder?ean i ple ents #ntity?ean 1 private long orderId5 private String order(a e5 private long lineIte Id5 33 -Y to the child ta"le IineIte s ta"le 33 child data fro IineIte s ta"le

private !ollection lineIte s5

pu"lic void ej"Ioad%& 1 33 step+, select orderId$ order(a e and lineIte Id fro ; pu"lic !ollection getIineIte s%&1 3X step., get lineIte s "y looking up IineIte , look up IineIte entity "ean /rder ta"le

ho e reference through K(>I

lineIte s 6 lineIte Ho e.findIineIte s%lineIte Id&5 X3 return lineIte s5 ; Here you load the data as and when client calls getIineIte s%& "ut not when it calls other "usiness ethods. So Ia@y loading is "est to i prove perfor ance and use it when you i ple ent relationships in #ntity "eans. Choose optimal transaction isolation level Isolation levels represent how a data"ase aintains data integrity against the pro"le s like dirty reads$ phanto reads and nonJrepeata"le reads which can occur due to concurrent transactions. )ou can avoid these pro"le s "y descri"ing following isolation levels in vendorLs deploy ent descriptor file%or other vendor specific anner& T0A(SA!TI/(O0#A>OA(!/**IT#> T0A(SA!TI/(O0#A>O!/**IT#> T0A(SA!TI/(O0#P#ATA?I#O0#A> T0A(SA!TI/(OS#0IAIIVA?I# The top ost is least isolation level and "otto ost is strict isolation level. >ata"ases use read and write locks depending on a"ove isolation levels to control transactions. Iet us first discuss the pro"le s related to concurrent transactions to the data"ase and then the re edy to these pro"le s. Pro"lems due to concurrent transactions The following ta"le descri"es isolation level against the pro"le Transaction Ievel >irty reads T0A(SA!TI/(O0#A>OA(!/**IT#> T0A(SA!TI/(O0#A>O!/**IT#> T0A(SA!TI/(O0#P#ATA?I#O0#A> T0A(SA!TI/(OS#0IAIIVA?I# )#S )#S (/ (/ (/ that it prevents ,

Per itted Pheno ena Perfor ance i pact (on 0epeata"le reads )#S )#S (/ (/ Phanto reads )#S )#S )#S (/ -AST#ST -AST *#>IA* SI/7

eans the transaction level does not prevent the pro"le

(/

eans the transaction level prevents the pro"le

?y setting isolation levels$ you are having an i pact on the perfor ance as entioned in the a"ove ta"le. >ata"ases use read and write locks to control a"ove isolation levels. Iet us have a look at each of these pro"le s$ and then look at the i pact on the perfor ance. irty read pro"lem 3 The following figure illustrates >irty read pro"le ,

Step +, Step ., Step C, Step D, Step E, Step F, Step G, Step H,

>ata"ase row has P0/>A!T 6 AMM+ and P0I!# 6 +M !onnection+ starts Transaction+ %T+& . !onnection. starts Transaction. %T.& . T+ updates P0I!# 6.M for P0/>A!T 6 AMM+ >ata"ase has now P0I!# 6 .M for P0/>A!T 6 AMM+ T. reads P0I!# 6 .M for P0/>A!T 6 AMM+ T. co its transaction

T+ roll"acks the transaction "ecause of so e pro"le

The pro"le is that T. gets wrong P0I!#6.M for P0/>A!T 6 AMM+ instead of +M "ecause of unco itted read. /"viously it is very dangerous in critical transactions if you read inconsistent data. If you are sure a"out not accessing data concurrently then you can allow this pro"le "y setting T0A(SA!TI/(O0#A>OA(!/**IT#> or T0A(SA!TI/(O(/(# elseT0A(SA!TI/(O0#A>O!/**IT#> to avoid this pro"le .

Unrepeata"le read pro"lem 3 The following figure illustrates Anrepeata"le read pro"le ,

Step +, Step ., Step C, Step D, Step E, Step F, Step G, Step H, Step N,

>ata"ase row has P0/>A!T 6 AMM+ and P0I!# 6 +M !onnection+ starts Transaction+ %T+& . !onnection. starts Transaction. %T.& . T+ reads P0I!# 6+M for P0/>A!T 6 AMM+ T. updates P0I!# 6 .M for P0/>A!T 6 AMM+ T. co its transaction

>ata"ase row has P0/>A!T 6 AMM+ and P0I!# 6 .M T+ reads P0I!# 6 .M for P0/>A!T 6 AMM+ T+ co its transaction

Here the pro"le is that Transaction+ reads +M first ti e and reads .M second ti e "ut it is supposed to "e +M always whenever it reads a record in that transaction. )ou can control this pro"le "y setting isolation level as T0A(SA!TI/(O0#P#ATA?I#O0#A>. Phantom read pro"lem 3 The following figure illustrates Phanto read pro"le ,

Step +, Step ., Step C, Step D, Step E,

>ata"ase has a row P0/>A!T 6 AMM+ and !/*PA()OI> 6 +M !onnection+ starts Transaction+ %T+& . !onnection. starts Transaction. %T.& . T+ selects a row with a condition S#I#!T P0/>A!T 7H#0# !/*PA()OI> 6 +M T. inserts a row with a condition I(S#0T P0/>A!T6AMM. 7H#0# !/*PA()OI>6 +M

Step F, Step G,

T. co

its transaction

>ata"ase has . rows with that condition

Step H, T+ select again with a condition S#I#!T P0/>A!T 7H#0# !/*PA()OI>6+M and gets . rows instead of + row Step N, T+ co its transaction

Here the pro"le is that T+ gets . rows instead of + row up on selecting the sa e condition second ti e. )ou can control this pro"le "y setting isolation level as T0A(SA!TI/(OS#0IAIIVA?I# Choosing a right isolation level for your program3 !hoosing a right isolation level for your progra depends upon your applicationLs require ent. In a single application itself the require ent generally changes$ suppose if you write a progra for searching a product catalog fro your data"ase then you can choose T0A(SA!TI/(O0#A>O A(!/**IT#> "ecause you need not worry a"out the isolation pro"le s $ so e other progra can insert records at the sa e ti e$ you donLt have to "other uch a"out that insertion. /"viously this i proves perfor ance significantly. If you write a critical progra like "ank or stocks analysis progra where you want to control all of the isolation pro"le s$ you can choose T0A(SA!TI/(OS#0IAIIVA?I# for axi u safety. Here it is the tradeoff "etween the safety and perfor ance.

/ther two isolation levels need good understanding of your require ent. If your application needs only co itted records$ then T0A(SA!TI/(O0#A>O!/**IT#> isolation is the good choice. If your application needs to read a row exclusively till you finish your work$ then T0A(SA!TI/(O0#P#ATA?I#O0#A> is the "est choice. 4ote, ?e aware of your data"ase serverLs support for these isolation levels. >ata"ase servers ay not support all of these isolation levels. /racle server supports only two isolation levels$ T0A(SA!TI/(O0#A>O!/**IT#> and T0A(SA!TI/(OS#0IAIIVA?I# isolation level$ default isolation level is T0A(SA!TI/(O0#A>O!/**IT#>. Use proper loc*ing strategy 7e discussed a"ove how a data"ase can lock data depending on isolation level. The locking that happens at data"ase level$ is called as data"ase locking strategy. /ther than that$ )our #K?Server3!ontainer can support different locking strategies. So e #K? vendors such as 7e"logic supports exclusive locking strategy that locks #ntity "eans at application server itself rather than at the data"ase. #xclusive locking "locks other #ntity "eans till locked #ntity "ean co pletes itLs transaction. This locking does not allow other "eans to even read the data $ it has an i pact on perfor ance. )our application server ay have default locking strategy of either data"ase locking or exclusive locking$ it ay have even other locking strategies. )ou need to configure your vendorLs deploy ent descriptor file so that you can override default locking strategy depending on your applicationLs require ent to i prove perfor ance. 5a*e read.only -ntity "eans In your #K? application$ your entity "eans ight "e always getting data fro the data"ase "ut not updating data. ?ut "y default$ your application server would read and write data using ej"Ioad%& and ej"Store%& ethods for every "usiness ethod call or end of transaction. 7hy would you update data"ase using ej"Store%& ethod while your entity "ean perfor s read only transactionsT this effects perfor ance "y calling unnecessary ej"Store%& ethods. In this situation$ if your #K?Server3!ontainer supports configuring for read only or readJwrite entity "eans$ it is "etter to configure as read only "eans in vendorLs deploy ent descriptor file to i prove perfor ance. If you configure your entity "ean as read only then there will "e no updates % no ej"Store%& calls& to the data"ase$ so "e careful when you configure this property. So e vendors support readJ ostly property where you can configure when to read fro data"ase$ you can also configure this feature if you need to reduce frequency of ej"Ioad%& calls. Iook at your vendorLs #K? server3container docu entation on how to configure read only property. Use dirty flag to avoid unchanged "uffer data updation #K? !ontainer calls ej"Store%& ethod when the "usiness ethod execution co pletes or when the transaction co pletes irrespective of change in the "eanLs data. The entity "eanLs data ay not change every ti e when the client calls the "usiness ethod. So there will "e lot of updates % calls to ej"Store%& & to the data"ase even though it doesnLt require$ thus degrading perfor ance. To avoid this pro"le $ you can configure dirty flag property in vendor specific deploy ent descriptor file for !*P+.+$ for exa ple isJ odifiedJ ethodJna e in we"logic serverLs we"logicJej"Jjar.x l file. -or #K?..M !*P$ it does not require to configure "ecause #K?..M !*P !ontainer supports this feature i plicitly. -or ?*P$ you need to write this ethod in "eanLs class and call this ethod wherever necessary. This technique reduces calls to the data"ase unless the "eanLs data changes$ thus i proving perfor ance. Commit the data after transaction

?y default$ )our #K? !ontainer either co its the data after every ethod call or after co pleting the whole transaction. -or exa ple$ in one transaction$ if you call four ethods of two entity "eans fro one session "ean ethod$ then the !ontainer can either co it the data after each of the entity "eans ethodLs execution that calls ej"Store%& ethod four ti es or it co its the data only once after execution of session "ean ethod with four entity "ean ethods that co pletes whole transaction. /"viously if the transaction co its after it finishes co pletely$ then it i proves perfor ance significantly. ?ut other clients cannot see the data till it co pletes transaction. If your #K? !ontainer3Server supports this feature$ you can configure this feature in vendorLs deploy ent descriptor or other vendor specific eans. -or exa ple$ we"logic serverLs we"logicJej"Jjar.x l has an ele ent LdelayJupdatesJuntilJendJ ofJtxL$ that updates the data"ase after co pletion of transaction. So co it the data after transaction "y configuring vendorLs file if you donLt need other clients to read transactional data in "etween. o "ul* updates If you use relationships %+,+$ +,*$ *,*& in !*P entity "eans and want to update "oth parent and child data %"ulk data&$ it is "etter to update the "oth parent and child data at the sa e ti e using vendor specific features. -or exa ple$ we"logic supports this feature as field groups. ?ulk updates reduces nu "er of calls to the data"ase and i proves perfor ance. Use C5P instead of B5P ?efore introduction of #K?..M specification often developers used ?*P rather than !*P "ecause the previous #K? spec does not support enough i portant features like relationships. ?ut #K?..M spec for !*P has good relationship support as well as perfor ance i prove ents. /ne of the !*P perfor ance i prove ent technique in #K?..M is that the !ontainer can onitor "eanLs data %inJ e ory "uffer& change and if any changes happens in that data then only !ontainer will update the data"ase. ?ecause of this onitoring capa"ility$ !*P gives "etter perfor ance than ?*P. And another technique is when you call finder ethod in ?*P$ it initially retrieves pri ary key with first call to the data"ase and then instance data "y placing a second call to the data"ase. It akes two calls to the data"ase. ?ut !*P gets the data with single call to the data"ase for the finder ethods. Thus !*P gives "etter perfor ance than ?*P "ecause !ontainer has good hold on !*P. Use e&"!ome() methods for glo"al operations #K?..M specification introduced ej"Ho e%& ethods in #ntity "eans. )ou can use these ethods to perfor glo"al operations % for exa ple$ getting total nu "er of persons& that do not relate to any specific entity "ean instance data. 7hen you call ho e ethods fro client$ the !ontainer calls the ej"Ho e%& ethod on the "ean that is in the instance pool "efore assigning any #K?/"ject to the client. This i proves perfor ance "ecause the "ean does not have state aintenance. So use ej"Ho e%& ethods for glo"al operations that do not have state %instance varia"les data& dependency. Use connection pool !reating a connection to the data"ase server is expensive. It is even ore expensive if the server is located on another achine. !onnection pool contains a nu "er of open data"ase connections$ and has open connections "etween ini u and axi u nu "er that you specify in vendor specific anner. The pool expands and shrinks "etween ini u and axi u si@e depending on incre ental capacity. )ou need to give ini u $ axi u and

incre ental si@es as properties to the pool in order to aintain that functionality. )ou get the connection fro the pool instead of getting it directly fro the data"ase. -or exa ple$ if you give properties like in$ ax and incre ental si@es as C$ +M and + then pool is created with si@e C initially and if it reaches its capacity C and if a client requests a connection concurrently$ it incre ents its capacity "y + till it reaches +M and later on it puts all itLs clients in a queue. )ou need to configure connection pool si@e in vendor specific anner and you need to to take care of properties like in$ ax and incre ent si@es. The axi u nu "er of connections to "e opened depend on your applicationLs require ent and the axi u nu "er of open connections your data"ase can support. In #K? deploy ent descriptor files$ you need to configure >ataSource reference that uses connection pool. )our #K? application i proves perfor ance significantly depending on connection pool si@e. So configure opti al connection pool to reduce expensive creation and destruction of data"ase connections thus i proving perfor ance significantly. Use % BC tuning techniques 7hen you write ?*P$ you need to write K>?! code on your own. K>?! has lot of techniques to i prove perfor ance. There is a separate section for K>?! in this site. Those techniques are Choosing the right Driver Optimization with Connection Set optimal row pre-fetch value Use Connection pool Control transaction Choose optimal isolation level Close Connection when finished

Optimization with Statement Choose right Statement interface Do batch update Do batch retrieval using Statement Close Statement when finished

Optimization with ResultSet Do batch retrieval using ResultSet Setup proper direction of processing rows Use proper get methods Close ResultSet when finished

Optimization with SQL Quer Cache the read-onl and read-mostl data !etch small amount of data iterativel rather than whole data at once "D#C $e %oints Ase these techniques in ?*P to "oost your ?*P perfor ance. Use direct % BC when dealing with huge data 'enerally developers prefer K>?! over entity "eans due to perfor ance considerations. #ntity "ean is a co ponent that has an overhead a"out which we discussed in !hoosing "etween #K? vs. nonJ#K?. /"viously #ntity "eans have advantages "ecause of their co ponent architecture. To get #K? architecture to so e extent you can wrap K>?! with session "eans. 7hen it co es to choosing "etween entity "eans versus K>?! calls$ you can decide depending on quantity of data. -or exa ple$ if you search data that retrieves EMMMM records$ K>?! is a "etter choice when co pared to entity "eans. #ntity "eans are not a pro"le with s all data and you can even increase perfor ance "y the techniques which we discussed. So use K>?! with session "eans when you deal with huge data to i prove perfor ance. Use "usiness logic in -ntity "eans )ou should consider an entity "ean not only as a data access o"ject "ut also as a "usiness o"ject. ?usiness logic depends purely on application "usiness require ent or on data. If you write "usiness ethods that depend on data in entity "ean$ it reduces network calls on re ote entity "eans "y reducing round trips for getting data. This works well when your entity "eans are re ote #K?s. So put "usiness logic that depends on data$ in re ote entity "eans there "y reducing network calls. #uning 5essage driven "eans The session "eans and entity "eans can act as K*S producers using K*S API "ut can only consu e essages synchronously using *essage!onsu er.receive%& ethod. The reason for synchronous consu ption of essages is that session and entity "eans i ple ent requestJreply process synchronously "ut not asynchronously$ that is why we have *essage driven "eans in #K?..M. *essage driven "eans consu e essages asynchronously fro K*S Server. 7e already discussed !o on tuning practices practices in #K? in the a"ove sections. So e of those practices such as !ache #K?Ho e o"ject references$ Ase !lustering for scala"ility$ Tune thread count$ are applica"le for *essage driven "eans also. Here we discuss a"out specific practices for *essage driven "eans. In order to get clear understanding of following tuning practices$ we will discuss *essage driven "ean life cycle first. 5essage driven "ean life cycle The life cycle of *essage driven "ean is analogous to the Stateless session "ean "ecause it also need not aintain client state. The ain difference "etween the is that Stateless "eans have "usiness ethods that are invoked "y clients where as *essage driven "eans have on*essage%& ethod of *essageIistener interface that has "usiness logic. The *essage driven "eans si ply connect to the K*S server$ consu e essages fro it and process those

essages. A *essage driven "ean does not have a re ote or ho e interface "ecause it is not an 0*I3II/P co ponent rather it uses K*S protocol to connect to the K*S server. The following figure illustrates the life cycle of *essage driven "ean.

)ou can control the nu "er of essage driven "eans "y entioning instance pool si@e in vendor specific deploy ent descriptor. This controls when the "eans are created$ re oved and call "ack ethods are called. -or exa ple in we"logicLs we"logicJej"Jjar.x l has ele ent for instance pool si@e$ that is 9pool: 9 axJ"eansJinJfreeJpool:+MM93 axJ"eansJinJfreeJpool: 9initialJ"eansJinJfreeJpool:EM93initialJ"eansJinJfreeJpool: 93pool: Here you can specify initial "eans and axi u "eans in the pool. If you ention for exa ple EM "eans in initial "eans and +MM for axi u "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 of the "ean. set*essage>riven!ontext%ctx& and ej"!reate%& ethods ethods

those EM "eans are ready for consu ing and processing EM concurrent essages. If the concurrent essages are ore than EM then the !ontainer creates ore "eans and calls the a"ove ethods till it reaches +MM "eans % axi u "eans in the pool&. So at any ti e the !ontainer can only have a axi u of +MM "eans to consu e essages concurrently. 7hat will happen if the concurrent essages are ore than +MMT well$ the container has to wait till "eans are availa"le in the pool. 7hen the essage arrives$ the container passes that essage to on*essage%*essage ethod of one of the "eans in the pool so that ethod can process "usiness logic. sg&

The !ontainer re oves the "eans fro the pool if the nu "er of essages arriving are not any. How the !ontainer re oves the "eans are depends upon itLs specific algorith s. At this ti e !ontainer calls ej"0e ove%& ethod of the "ean and destroys the "ean fro the pool. The creation and destruction of "eans occurs depending on instance pool si@e and consu ption %or arrival of essages to the >estination& of essages. 7ith this discussion$ we understand the i portance of pool si@e and when the call "ack ethods are executed in *essage driven "eans. (ow let us discuss how we can tune *essage driven "eans. #une 5essage driven "eans instance pool size The creation and destruction of "eans is expensive. To reduce this cost$ the #K? !ontainer3Server creates pool of "eans %that is vendor specific&$ you need to give opti al pool si@e for "etter perfor ance. As we discussed a"ove$ you can give this pool si@e % initial "eans and axi u "eans& for exa ple in we"logicLs we"logicJej"Jjar.x l has an ele ent 9pool:. See your vendor docu entation for ore infor ation. The axi u nu "er of "eans in the pool effects perfor ance. If this is less$ then the !ontainer has to put the essages in the wait ode in the K*S server when the nu "er of essages arriving are ore than the ax pool si@e. It degrades the perfor ance and takes ore ti e to execute. -or "est perfor ance$ give axi u "eans in the pool as equal to expected nu "er of axi u concurrent essages. Use set5essage rivenConte1t() or e&"Create() method as cache In *essage driven "ean life cycle$ the container invokes the set*essage>riven!ontext%& and ej"!reate%& ethods only once in itLs life ti e when it creates the "ean instance first ti e and puts it in the pool and later it will "e used for the processing other essages till it is re oved "y the !ontainer$)ou can use these ethods to acquire resources like !onnection-actory references$ >estination references$ ho e o"jects references of other session or entity "eans or >ataSource references and assign to the instance varia"les. /nce you acquire these resources in these ethods you need not create resources for processing other essages "ecause those resources are already acquired and availa"le for other essage processes. /"viously these resources will "e specific to a "ean "ut will not "e availa"le glo"ally. -or glo"al reuse$ it is "etter to use the technique that we already discussed in !ache #K?Ho e o"ject references$ you can use this technique to acquire other resources also. 0e e "er that you should not acquire physical resources like data"ase connections in these ethods if the concurrent arrival of essages are ore and pool si@e is ore$ it is "etter to acquire those type of resources in on*essage%& ethod and re ove in the sa e ethod. Ase set*essage>riven!ontext%& and ej"!reate%& ethods to cache "ean specific resources that are needed for other clients. 0emove resources in e&"0emove()

In *essage driven "eans$ the !ontainer calls ej"0e ove%& ethod just "efore re oving a "ean fro the pool like Stateless session "eans. So whatever resources you acquired in your "ean %as discussed a"ove& need to "e released in this ethod. Use %5S tuning techniques 7e have separate section for K*S$ See ?est practices to i prove perfor ance in K*S. Those practices are eant for "oth K*S producers and K*S consu ers. )ou can specifically look at !onsu er techniques %*essage driven "ean act as consu er& to i prove overall perfor ance of *essage driven "eans. See Optimization with Connection Start the Connection when appropriate %rocess messages concurrentl Close the Connection when finished

Optimization with Session Choose proper ac&nowledgement mode Control transaction Close the Session when finished

Optimization with Destination Optimization with 'essage %roducer(Consumer Choose non-durable messages where appropriate Set )ime)oLive value properl Receive messages as nchronousl Close %roducer(Consumer when finished

Optimization with 'essage Choosing right "'S Server "'S $e %oints Ase these techniques to "oost your *essage driven "eanLs perfor ance. $ey Points Common tuning practices for -%Bs +. Ase Iocal interfaces that are availa"le in #K?..M if you deploy "oth #K? !lient and #K?

in the sa e #K? Server. .. Ase Uendor specific passJ"yJreference i ple entation to ake #K?+.+ re ote #K?s as Iocal #K?s if you deploy "oth #K? !lient and #K? in the sa e #K? Server. C. 7rap entity "eans with session "eans to reduce network calls and to pro ote declarative transactions. /ptionally$ ake entity "eans as local "eans where appropriate. D. *ake coarse grained session and entity "eans to reduce network calls. E. !ontrol seriali@ation "y odifying unnecessary data varia"les with LtransientL key word to avoid unnecessary data transfer over network. F. !ache #K?Ho e references to avoid K(>I lookup overhead. G. Avoid transaction overhead for nonJtransactional ethods of session "eans "y declaring L(otSupportedL or L(everL transaction attri"utes that avoid further propagation of transactions. H. Set proper transaction age%ti eJout& to avoid large transaction. N. Ase clustering for scala"ility. +M. Tune thread count for #K? Server to increase #K? Server capacity. ++. !hoose servletLs HttpSession o"ject rather than Stateful session "ean to aintain client state if you donLt require co ponent architecture and services of Stateful session "ean. +.. !hoose "est #K? Server "y testing with #!perf tool kit. +C. !hoose nor al java o"ject over #K? if you donLt want "uiltJin services such as 0*I3II/P$ transactions$ security$ persistence$ resource pooling$ thread safe$ client state etc.. Stateless session "eans +. Tune the Stateless session "eans pool si@e to avoid overhead of creation and destruction of "eans. .. Ase setSession!ontext%& or ej"!reate%& ethod to cache "ean specific resources. C. 0elease acquired resources in ej"0e ove%& ethod Stateful session "eans +. Tune Stateful session "eans cache si@e to avoid overhead of activation and passivation process. .. Set opti al Stateful session "ean age%ti eJout& to avoid resource congestion. C. Ase LtransientL key word for unnecessary varia"les of Stateful session "ean to avoid seriali@ation overhead. D. 0e ove Stateful session "eans explicitly fro client using re ove%& ethod. -ntity "eans +. Tune the entity "eans pool si@e to avoid overhead of creation and destruction of "eans. .. Tune the entity "eans cache si@e to avoid overhead of activation$ passivation and data"ase calls. C. Ase set#ntity!ontext%& ethod to cache "ean specific resources. D. 0elease acquired resources in unSet#ntity!ontext%& ethod E. Ase Ia@y loading to avoid unnecessary preJloading of child data. F. !hoose opti al transaction isolation level to avoid "locking of other transactional clients. G. Ase proper locking strategy. H. *ake readJonly entity "eans for read only operations. N. Ase dirty flag to avoid unchanged "uffer data updation. +M. !o it the data after the transaction co pletes to reduce data"ase calls in "etween transaction. ++. >o "ulk updates to reduce data"ase calls. +.. Ase !*P rather than ?*P to utili@e "uiltJin perfor ance opti i@ation facilities of !*P. +C. Ase ej"Ho e%& ethods for glo"al operations. +D. Tune connection pool si@e to reduce overhead of creation and destruction of data"ase connections. +E. Ase K>?! tuning techniques in ?*P.

+F. Ase direct K>?! rather than using entity "eans when dealing with huge data such as searching a large data"ase. +G. Ase "usiness logic that is specific to entity "ean data. 5essage driven "eans +. Tune the *essage driven "eans pool si@e to pro ote concurrent processing of essages. .. Ase set*esssage>riven!ontext%& or ej"!reate%& ethod to cache "ean specific resources. C. 0elease acquired resources in ej"0e ove%& ethod. D. Ase K*S tuning techniques in *essage driven "eans.

Overview of % BC
K>?! defines how a Kava progra can co unicate with a data"ase. This section focuses ainly on K>?! ..M API. K>?! API provides two packages they are java.sql and javax.sql . ?y using K>?! API$ you can connect virtually any data"ase$ send SZI queries to the data"ase and process the results. K>?! architecture defines different layers to work with any data"ase and java$ they are K>?! API interfaces and classes which are at top ost layer% to work with java &$ a driver which is at iddle layer %i ple ents the K>?! API interfaces that aps java to data"ase specific language& and a data"ase which is at the "otto %to store physical data&. The following figure illustrates the K>?! architecture.

K>?! API provides interfaces and classes to work with data"ases. !onnection interface encapsulates data"ase connection functionality$ State ent interface encapsulates SZI query representation and execution functionality and 0esultSet interface encapsulates retrieving data which co es fro execution of SZI query using State ent. The following are the "asic steps to write a K>?! progra

+. I port java.sql and javax.sql packages .. Ioad K>?! driver C. #sta"lish connection to the data"ase using !onnection interface D. !reate a State ent "y passing SZI query E. #xecute the State ent F. 0etrieve results "y using 0esultSet interface G. !lose State ent and !onnection 7e will look at these areas one "y one$ what type of driver you need to load$ how to use !onnection interface in the "est anner$ how to use different State ent interfaces$ how to process results using 0esultSet and finally how to opti i@e SZI queries to i prove K>?! perfor ance. (ote+, )our K>?! driver should "e fully co pati"le with K>?! ..M features in order to use so e of the suggestions entioned in this section. (ote., This Section assu es that reader has so e "asic knowledge of K>?!.

Choosing right river Here we will walk through initially a"out the types of drivers$ availa"ility of drivers$ use of drivers in different situations$ and then we will discuss a"out which driver suits your application "est. >river is the key player in a K>?! application$ it acts as a ediator "etween Kava application and data"ase. It i ple ents K>?! API interfaces for a data"ase$ for exa ple /racle driver for oracle data"ase$ Sy"ase driver for Sy"ase data"ase. It aps Kava language to data"ase specific language including SZI. K>?! defines four types of drivers to work with. >epending on your require ent you can choose one a ong the . Here is a "rief description of each type of driver , Type of Tier driver +

>river

echanis

>escription

This driver converts K>?! calls to />?! calls through K>?!J/>?! ?ridge driver which in turn Two K>?!J/>?! converts to data"ase calls. !lient requires />?! li"raries. This driver converts K>?! calls to data"ase Two (ative API J Partly J Kava driver specific native calls. !lient requires data"ase specific li"raries. This driver passes calls to proxy server through network protocol which in turn converts to Three K>?! J (et JAll Kava driver data"ase calls and passes through data"ase specific protocol. !lient doesnLt require any driver. This driver directly calls data"ase. !lient doesnLt Two (ative protocol J All J Kava driver require any driver.

/"viously the choice of choosing a driver depends on availa"ility of driver and require ent. 'enerally all the data"ases support their own drivers or fro third party vendors. If you donLt have driver for your data"ase$ K>?!J/>?! driver is the only choice "ecause all ost all the vendors support />?!. If you have tiered require ent % two tier or three tier& for your application$ then you can filter down your choices$ for exa ple if your application is three tiered$ then you can go for Type three driver "etween client and proxy server shown "elow. If you want to connect to data"ase fro java applet$ then you have to use Type four driver "ecause it is only the driver which supports that feature. This figure shows the overall picture of drivers fro tiered perspective.

This figure illustrates the drivers that can "e used for two tiered and three tiered applications. -or "oth two and three tiered applications$ you can filter down easily to Type three driver "ut you can use Type one$ two and four drivers for "oth tiered applications. To "e ore precise$ for java applications% nonJapplet& you can use Type one$ two or four driver. Here is exactly where you ay ake a istake "y choosing a driver without taking perfor ance into consideration. Iet us look at that perspective in the following section. Type C [ D drivers are faster than other drivers "ecause Type C gives facility for opti i@ation techniques provided "y application server such as connection pooling$ caching$ load "alancing etc and Type D driver need not translate data"ase calls to />?! or native connectivity interface. Type + drivers are slow "ecause they have to convert K>?! calls to />?! through K>?!J/>?! ?ridge driver initially and then />?! >river converts the into data"ase specific calls. Type . drivers give average perfor ance when co pared to Type C [ D drivers "ecause the data"ase calls have to "e converted into data"ase specific calls. Type . drivers give "etter perfor ance than Type + drivers. -inally$ to i prove perfor ance +. Ase Type D driver for applet to data"ase co unication.

.. Ase Type . driver for two tiered applications for co unication "etween java client and the data"ase that gives "etter perfor ance when co pared to Type+ driver C. Ase Type + driver if your data"ase doesnLt support a driver. This is rare situation "ecause al ost all ajor data"ases support drivers or you will get the fro third party vendors. D.Ase Type C driver to co unicate "etween client and proxy server % we"logic$ we"sphere etc& for three tiered applications that gives "etter perfor ance when co pared to Type + [ . drivers.

Optimization with Connection

java.sql package in K>?! provides !onnection interface that encapsulates data"ase connection functionality. Asing !onnection interface$ you can fine tune the following operations , +. Set opti al row preJfetch value .. Ase !onnection pool C. !ontrol transaction D. !hoose opti al isolation level E. !lose !onnection when finished #ach of these operations effects the perfor ance. 7e will walk through each operation one "y one. +6 Set optimal row pre.fetch value 7e have different approaches to esta"lish a connection with the data"ase$ the first type of approach is , +. >river*anager.get!onnection%String url& .. >river*anager.get!onnection%String url$ Properties props& C. >river*anager.get!onnection%String url$ String user$ String password& D. >river.connect%String url$ Properties props& 7hen you use this approach$ you can pass data"ase specific infor ation to the data"ase "y passing properties using Properties o"ject to i prove perfor ance. -or exa ple$ when you use oracle data"ase you can pass default nu "er of rows that ust "e preJfetched fro the data"ase server and the default "atch value that triggers an execution request. /racle has default value as +M for "oth properties. ?y increasing the value of these properties$ you can reduce the nu "er of data"ase calls which in turn i proves perfor ance. The following code snippet illustrates this approach. java.util.Properties props 6 new java.util.Properties%&5 props.put%8user8$8scott8&5 props.put%8password8$8tiger8&5 props.put%8default0owPrefetch8$8CM8&5 props.put%8default?atchUalue8$8E8&5 !onnection con 6 >river*anger.get!onnection%8jd"c,oracle,thin,Qhoststring8$ props&5 )ou need to figure out appropriate values for a"ove properties for "etter perfor ance depending on applicationLs require ent. Suppose$ you want to set these properties for search facility$ you can increase default0owPrefetch so that you can increase perfor ance significantly. The second type of approach is to get connection fro >ataSource.

)ou can get the connection using javax.sql.>ataSource interface. The advantage of getting connection fro this approach is that the >ataSource works with K(>I. The i ple entation of >ataSource is done "y vendor$ for exa ple you can find this feature in we"logic$ we"sphere etc. The vendor si ply creates >ataSource i ple entation class and "inds it to the K(>I tree. The following code shows how a vendor creates i ple entation class and "inds it to K(>I tree.

>ataSourceI pl dsi 6 new >ataSourceI pl%&5 dsi.setServer(a e%8oracleHi8&5 dsi.set>ata"ase(a e%8>e o8&5 !ontext ctx 6 new Initial!ontext%&5 ctx."ind%8jd"c3de o>?8$ dsi&5 This code registers the >ataSourceI pl o"ject to the K(>I tree$ then the progra er can get the >ataSource reference fro K(>I tree without knowledge of the underlying technology. !ontext ctx 6 new Initial!ontext%&5 >ataSource ds 6 %>ataSource&ctx.lookup%8jd"c3de o>?8&5 !onnection con 6 ds.get!onnection%&5 ?y using this approach we can i prove perfor ance. (early all ajor vendor application servers like we"logic$ we"shpere i ple ent the >ataSource "y taking connection fro connection pool rather than a single connection every ti e. The application server creates connection pool "y default. 7e will discuss the advantage of connection pool to i prove perfor ance in the next section. ,6 Use Connection pool !reating a connection to the data"ase server is expensive. It is even ore expensive if the server is located on another achine. !onnection pool contains a nu "er of open data"ase connections with ini u and axi u connections$ that eans the connection pool has open connections "etween ini u and axi u nu "er that you specify. The pool expands and shrinks "etween ini u and axi u si@e depending on incre ental capacity. )ou need to give ini u $ axi u and incre ental si@es as properties to the pool in order to aintain that functionality. )ou get the connection fro the pool rather directly .-or exa ple$ if you give properties like in$ ax and incre ental si@es as C$ +M and + then pool is created with si@e C initially and if it reaches itLs capacity C and if a client requests a connection concurrently$ it incre ents its capacity "y + till it reaches +M and later on it puts all its clients in a queue. There are a few choices when using connection pool. +. )ou can depend on application server if it supports this feature$ generally all the application servers support connection pools. Application server creates the connection pool on "ehalf of you when it starts. )ou need to give properties like in$ ax and incre ental si@es to the application server. .. )ou can use K>?! ..M interfaces$ !onnectionPool>ataSource and Pooled!onnection if your driver i ple ents these interfaces C. /r you can create your own connection pool if you are not using any application server or K>?! ..M co pati"le driver. ?y using any of these options$ you can increase perfor ance significantly. )ou need to take care of properties like in$ ax and incre ental si@es. The axi u nu "er of connections to "e given depends on your applicationLs require ent that eans how any concurrent clients can access your data"ase and also it depends up on your data"aseLs capa"ility to provide axi u nu "er of connections. 76 Control transaction In general$ transaction represents one unit of work or "unch of code in the progra that executes in itLs entirety or none at all. To "e precise$ it is all or no work. In K>?!$ transaction is a set of one or ore State ents that execute as a single unit.

java.sql.!onnection interface provides so e pu"lic interface !onnection 1 "oolean getAuto!o void void void ; K>?!Ls default echanis for transactions, setAuto!o co it%&5 it%&5

ethods to control transaction they are

it%"oolean autoco

it&5

roll"ack%&5

?y default in K>?! transaction starts and co its after each state entLs execution on a connection. That is the Auto!o it ode is true. Progra er need not write a co it%& ethod explicitly after each state ent. /"viously this default echanis gives good facility for progra ers if they want to execute a single state ent. ?ut it gives poor perfor ance when ultiple state ents on a connection are to "e executed "ecause co it is issued after each state ent "y default$ that in turn reduces perfor ance "y issuing unnecessary co its. The re edy is to flip it "ack to Auto!o it ode as false and issue co it%& ethod after a set of state ents execute$ this is called as "atch transaction. Ase roll"ack%& in catch "lock to roll"ack the transaction whenever an exception occurs in your progra . The following code illustrates the "atch transaction approach. try1 connection.setAuto!o it%false&5

PreparedState ent ps 6 connection.preareState ent% 8AP>AT# e ployee S#T Address6T 7H#0# na e6T8&5 ps.setString%+$8Austin8&5 ps.setString%.$8008&5 ps.executeApdate%&5 PreparedState ent ps+ 6 connection.prepareState ent% 8AP>AT# account S#T salary6T 7H#0# na e6T8&5 ps+.set>ou"le%+$ EMMM.MM&5 ps+.setString%.$8008&5 ps+.executeApdate%&5 connection.co it%&5 it%true&5

connection.setAuto!o

;catch%SZI#xception e&1 connection.roll"ack%&5; finally1 if%ps R6 null&1 ps.close%&5; if%ps+ R6 null&1ps+.close%&5; if%connection R6 null&1connection.close%&5; ;

This "atch transaction gives good perfor ance "y reducing co state entLs execution. 86 Choose optimal isolation level

it calls after each

Isolation level represent how a data"ase aintains data integrity against the pro"le s like dirty reads$ phanto reads and nonJrepeata"le reads which can occur due to concurrent transactions. java.sql.!onnection interface provides ethods and constants to avoid the a"ove entioned pro"le s "y setting different isolation levels. pu"lic interface !onnection 1 pu"lic static final int T0A(SA!TI/(O(/(# pu"lic static final int T0A(SA!TI/(O0#A>O!/**ITT#> pu"lic static final int T0A(SA!TI/(O0#A>OA(!/**ITT#> pu"lic static final int T0A(SA!TI/(O0#P#ATA?I#O0#A> pu"lic static final int T0A(SA!TI/(OS#0IAIIVA?I# int void ; )ou can get the existing isolation level with getTransactionIsolation%& ethod and set the isolation level with setTransactionIsolation%int isolationlevelconstant& "y passing a"ove constants to this ethod. The following ta"le descri"es isolation level against the pro"le that it prevents , Perfor ance i pact Phanto reads (3A )#S )#S )#S (/ getTransactionIsolation%&5 setTransactionIsolation%int isolationlevelconstant&5 6M 6. 6+ 6D 6H

Per itted Pheno ena >irty (on 0epeata"le reads reads T0A(SA!TI/(O(/(# (3A (3A T0A(SA!TI/(O0#A>OA(!/**IT#> )#S )#S T0A(SA!TI/(O0#A>O!/**IT#> (/ )#S T0A(SA!TI/(O0#P#ATA?I#O0#A> (/ (/ T0A(SA!TI/(OS#0IAIIVA?I# (/ (/ Transaction Ievel )#S (/ eans that the Isolation level does not prevent the pro"le eans that the Isolation level prevents the pro"le

-AST#ST -AST#ST -AST *#>IA* SI/7

?y setting isolation levels$ you are having an i pact on the perfor ance as entioned in the a"ove ta"le. >ata"ase use read and write locks to control a"ove isolation levels. Iet us have a look at each of these pro"le s and then look at the i pact on the perfor ance. irty read pro"lem 3 The following figure illustrates >irty read pro"le ,

Step +, Step ., Step C, Step D, Step E, Step F, Step G, Step H,

>ata"ase row has P0/>A!T 6 AMM+ and P0I!# 6 +M !onnection+ starts Transaction+ %T+& . !onnection. starts Transaction. %T.& . T+ updates P0I!# 6.M for P0/>A!T 6 AMM+ >ata"ase has now P0I!# 6 .M for P0/>A!T 6 AMM+ T. reads P0I!# 6 .M for P0/>A!T 6 AMM+ T. co its transaction

T+ roll"acks the transaction "ecause of so e pro"le

The pro"le is that T. gets wrong P0I!#6.M for P0/>A!T 6 AMM+ instead of +M "ecause of unco itted read. /"viously it is very dangerous in critical transactions if you read inconsistent data. If you are sure a"out not accessing data concurrently then you can allow this pro"le "y setting T0A(SA!TI/(O0#A>OA(!/**IT#> or T0A(SA!TI/(O(/(# that in turn i proves perfor ance otherwise you have to use T0A(SA!TI/(O0#A>O!/**IT#> to avoid this pro"le .

Unrepeata"le read pro"lem 3 The following figure illustrates Anrepeata"le read pro"le ,

Step +, Step ., Step C, Step D, Step E, Step F, Step G, Step H, Step N,

>ata"ase row has P0/>A!T 6 AMM+ and P0I!# 6 +M !onnection+ starts Transaction+ %T+& . !onnection. starts Transaction. %T.& . T+ reads P0I!# 6+M for P0/>A!T 6 AMM+ T. updates P0I!# 6 .M for P0/>A!T 6 AMM+ T. co its transaction

>ata"ase row has P0/>A!T 6 AMM+ and P0I!# 6 .M T+ reads P0I!# 6 .M for P0/>A!T 6 AMM+ T+ co its transaction

Here the pro"le is that Transaction+ reads +M first ti e and reads .M second ti e "ut it is supposed to "e +M always whenever it reads a record in that transaction. )ou can control this pro"le "y setting isolation level as T0A(SA!TI/(O0#P#ATA?I#O0#A>. Phantom read pro"lem 3 The following figure illustrates Phanto read pro"le ,

Step +, Step ., Step C, Step D, Step E,

>ata"ase has a row P0/>A!T 6 AMM+ and !/*PA()OI> 6 +M !onnection+ starts Transaction+ %T+& . !onnection. starts Transaction. %T.& . T+ selects a row with a condition S#I#!T P0/>A!T 7H#0# !/*PA()OI> 6 +M T. inserts a row with a condition I(S#0T P0/>A!T6AMM. 7H#0# !/*PA()OI>6 +M

Step F, Step G,

T. co

its transaction

>ata"ase has . rows with that condition

Step H, T+ select again with a condition S#I#!T P0/>A!T 7H#0# !/*PA()OI>6+M and gets . rows instead of + row Step N, T+ co its transaction

Here the pro"le is that T+ gets . rows instead of + row up on selecting the sa e condition second ti e. )ou can control this pro"le "y setting isolation level as T0A(SA!TI/(OS#0IAIIVA?I# Choosing a right isolation level for your program3 !hoosing a right isolation level for your progra depends upon your applicationLs require ent. In single application itself the require ent generally changes$ suppose if you write a progra for searching a product catalog fro your data"ase then you can easily choose T0A(SA!TI/(O0#A>OA(!/**IT#> "ecause you need not worry a"out the pro"le s that are entioned a"ove$ so e other progra can insert records at the sa e ti e$ you donLt have to "other uch a"out that insertion. /"viously this i proves perfor ance significantly. If you write a critical progra like "ank or stocks analysis progra where you want to control all of the a"ove entioned pro"le s$ you can choose T0A(SA!TI/(OS#0IAIIVA?I# for axi u safety. Here it is the tradeoff "etween the safety and perfor ance. Alti ately we need safety here.

If you donLt have to deal with concurrent transactions your application$ then the "est choice is T0A(SA!TI/(O(/(# to i prove perfor ance. /ther two isolation levels need good understanding of your require ent. If your application needs only co itted records$ then T0A(SA!TI/(O0#A>O!/**IT#> isolation is the good choice. If your application needs to read a row exclusively till you finish your work$ then T0A(SA!TI/(O0#P#ATA?I#O0#A> is the "est choice. 4ote, ?e aware of your data"ase serverLs support for these isolation levels. >ata"ase servers ay not support all of these isolation levels. /racle server supports only two isolation levels$ T0A(SA!TI/(O0#A>O!/**IT#> and T0A(SA!TI/(OS#0IAIIVA?I# isolation level$ default isolation level is T0A(SA!TI/(O0#A>O!/**IT#>. 96 Close Connection when finished !losing connection explicitly allows gar"age collector to recollect e ory as early as possi"le. 0e e "er that when you use the connection pool$ closing connection eans that it returns "ack to the connection pool rather than closing direct connection to the data"ase. Optimization with Statement State ent interface represents SZI query and execution and they provide nu "er of ethods and constants to work with queries. They also provide so e ethods to fine tune perfor ance. Progra er ay overlook these fine tuning ethods that result in poor perfor ance. The following are the tips to i prove perfor ance "y using state ent interfaces +. !hoose the right State ent interface .. >o "atch update C. >o "atch retrieval using State ent .. !lose State ent when finished +6 Choose right Statement interface There are three types of State ent interfaces in K>?! to represent the SZI query and execute that query$ they are State ent$ PreparedState ent and !alla"leState ent. State ent is used for static SZI state ent with no input and output para eters$ PreparedState ent is used for dyna ic SZI state ent with input para eters and !alla"leState ent is used for dyna ic SZI sate ent with "oth input and output para eters$ "ut PreparedState ent and !alla"leState ent can "e used for static SZI state ents as well. !alla"leState ent is ainly eant for stored procedures. PreparedState ent gives "etter perfor ance when co pared to State ent "ecause it is preJ parsed and preJco piled "y the data"ase once for the first ti e and then onwards it reuses the parsed and co piled state ent. ?ecause of this feature$ it significantly i proves perfor ance when a state ent executes repeatedly$ It reduces the overload incurred "y parsing and co piling. !alla"leState ent gives "etter perfor ance when co pared to PreparedState ent and State ent when there is a require ent for single request to process ultiple co plex state ents. It parses and stores the stored procedures in the data"ase and does all the work at data"ase itself that in turn i proves perfor ance. ?ut we loose java porta"ility and we have to depend up on data"ase specific stored procedures. ,6 o "atch update )ou can send ultiple queries to the data"ase at a ti e using "atch update feature of state ent o"jects this reduces the nu "er of K>?! calls and i proves perfor ance. Here is an exa ple of how you can do "atch update$

state ent.add?atch% 8sql query+8&5 state ent.add?atch%8 sql query.8&5 state ent.add?atch%8 sql queryC8&5 state ent.execute?atch%&5 All three types of state ents have these 76 o "atch retrieval using Statement )ou can get the default nu "er of rows that is provided "y the driver. )ou can i prove perfor ance "y increasing nu "er of rows to "e fetched at a ti e fro data"ase using set-etchSi@e%& ethod of the state ent o"ject. Initially find the default si@e "y using State ent.get-etchSi@e%&5 and then set the si@e as per your require ent State ent.set-etchSi@e%CM&5 Here it retrieves CM rows at a ti e for all result sets of this state ent. 86 Close Statement when finished !lose state ent o"ject as soon as you finish working with that$ it explicitly gives a chance to gar"age collector to recollect e ory as early as possi"le which in turn effects perfor ance. State ent.close%&5 Optimization with 0esultSet 0esultSet interface represents data that contains the results of executing an SZI Zuery and it provides a nu "er of ethods and constants to work with that data. It also provides ethods to fine tune retrieval of data to i prove perfor ance. The following are the fine tuning tips to i prove perfor ance "y using 0esultSet interface. +. >o "atch retrieval using 0esultSet .. Set up proper direction for processing the rows C. Ase proper get ethods ethods to do "atch update.

D. !lose 0esultSet when finished +6 o "atch retrieval using 0esultSet 0esultSet interface also provides "atch retrieval facility like State ent as overrides the State ent "ehaviour. Initially find the default si@e "y using 0esultSet.get-etchSi@e%&5 and then set the si@e as per require ent 0esultSet.set-etchSi@e%EM&5 This feature significantly i proves perfor ance when you are dealing with retrieval of large nu "er of rows like search functionality. ,6 Setup proper direction of processing rows 0esultSet has the capa"ility of setting the direction in which you want to process the results$ it has three constants for this purpose$ they are -#T!HO-/07A0>$ -#T!HO0#U#0S#$ -#T!HOA(Y(/7( entioned a"ove. It

Initially find the direction "y using 0esultSet.get-etch>irection%&5 and then set the direction accordingly 0esultSet.set-etch>irection%-#T!HO0#U#0S#&5 76 Use proper get111() methods 0esultSet interface provides lot of getxxx%& ethods to get and convert data"ase data types to java data types and is flexi"ile in converting non feasi"le data types. -or exa ple$ getString%String colu n(a e& returns java String o"ject. colu n(a e is reco ended to "e a UA0!HA0 /0 !HA0 type of data"ase "ut it can also "e a (A*#0I!$ >AT# etc. If you give non reco ended para eters$ it needs to cast it to proper java data type that is expensive. -or exa ple consider that you select a productLs id fro huge data"ase which returns illions of records fro search functionality$ it needs to convert all these records that is very expensive. So always use proper getxxx%& ethods according to K>?! reco endations.

86 Close 0esultSet when finished !lose 0esultSet o"ject as soon as you finish working with 0esultSet o"ject even though State ent o"ject closes the 0esultSet o"ject i plicitly when it closes$ closing 0esultSet explicitly gives chance to gar"age collector to recollect e ory as early as possi"le "ecause 0esultSet o"ject ay occupy lot of e ory depending on query. 0esultSet.close%&5

Optimization with S:2 :uery This is one of the area where progra If you give a query like State ent st t 6 connection.createState ent%&5 0esultSet rs 6 st t.executeZuery%8select X fro e ployee where na e6008&5 ay not need all the colu n data ers generally ake a istake

The returned result set contains all the colu ns data. you and want only salary for 00. The "etter query is 8select salary fro

e ployee where na e6008

It returns the required data and reduces unnecessary data retrieval.

Cache the read.only and read.mostly data #very data"ase sche a generally has readJonly and readJ ostly ta"les. These ta"les are called as lookup ta"les. 0eadJonly ta"les contain static data that never changes in its life ti e. 0eadJ ostly ta"les contain se i dyna ic data that changes often. There will not "e any sort of writing operations in these ta"les. If an application reads data fro these ta"les for every client request$ then it is redundant$ unnecessary and expensive. The solution for this pro"le is to cache the readJonly ta"le data "y reading the data fro that ta"le once and caching the readJ ostly ta"le data "y reading and refreshing with ti e li it. This solution i proves perfor ance significantly. See the following link for source code of such caching echanis .

http,33www.javaworld.co 3javaworld3jwJMGJ.MM+3jwJMG.MJcache.ht l )ou can tweak this code as per application require ent. -or readJonly data$ you need not refresh data in its life ti e. -or readJ ostly data$ you need to refresh the data with ti e li it. It is "etter to set this refreshing ti e li it in properties file so that it can "e changed at any ti e.

;etch small amount of data iteratively instead of fetching whole data at once Applications generally require to retrieve huge data fro the data"ase using K>?! in operations like searching data. If the client request for a search$ the application ight return the whole result set at once. This process takes lot of ti e and has an i pact on perfor ance. The solution for the pro"le is +. !ache the search data at the serverJside and return the data iteratively to the client. -or exa ple$ the search returns +MMM records$ return data to the client in +M iterations where each iteration has +MM records. .. Ase Stored procedures to return data iteratively. This does not use serverJside caching rather serverJside application uses Stored procedures to return s all a ount of data iteratively. /ut of these solutions the second solution gives "etter perfor ance "ecause it need not keep the data in the cache %inJ e ory&. The first procedure is useful when the total a ount of data to "e returned is not huge.

$ey Points +. Ase Type two driver for two tiered applications to co unicate fro java client to data"ase that gives "etter perfor ance than Type+ driver. .. Ase Type four driver for applet to data"ase co unication that is two tiered applications and three tiered applications when co pared to other drivers. C. Ase Type one driver if you donLt have a driver for your data"ase. This is a rare situation "ecause all ajor data"ases support drivers or you will get a driver fro third party vendors. D. Ase Type three driver to co unicate "etween client and proxy server % we"logic$ we"sphere etc& for three tiered applications that gives "etter perfor ance when co pared to Type + [. drivers. E. Pass data"ase specific properties like defaultPrefetch if your data"ase supports any of the . F. 'et data"ase connection fro connection pool rather than getting it directly G. Ase "atch transactions. H. !hoose right isolation level as per your require ent. T0A(SA!TI/(O0#A>OA(!/**IT#> gives "est perfor ance for concurrent transaction "ased applications. T0A(SA!TI/(O(/(# gives "est perfor ance for nonJconcurrent transaction "ased applications. N. )our data"ase server ay not support all isolation levels$ "e aware of your data"ase server features. +M. Ase PreparedState ent when you execute the sa e state ent ore than once. ++. Ase !alla"leState ent when you want result fro ultiple and co plex state ents for a single request. +.. Ase "atch update facility availa"le in State ents. +C. Ase "atch retrieval facility availa"le in State ents or 0esultSet. +D. Set up proper direction for processing rows. +E. Ase proper getWWW%& ethods. +F. !lose 0esultSet$ State ent and !onnection whenever you finish your work with the .

+G. 7rite precise SZI queries. +H. !ache readJonly and readJ ostly ta"les data. +N. -etch s all a ount of data iteratively rather than whole data at once when retrieving large a ount of data like searching data"ase etc.

Overview of Patterns
Pattern is a solution to a recurring pro"le in a context. /nce Pattern %solution& is developed fro a recurring pro"le it can "e reused without reinventing the solution again. Patterns are populari@ed "y the classic "ook Design Patterns: Elements of Reusable Object-Oriented Software$ "y #rich 'a a$ 0ichard Hel $ 0alph Kohnson$ and Kohn Ulissides$ also called as '/- %'ang of -our& representing four authors who wrote that "ook. Specifically for K.## pro"le s and solutions$ we have now Core J EE Patterns! Best Practices and Design Strategies "y Sun Kava !enter and EJB Design Patterns "y TheServerSide.co . This section ainly focuses on perfor ance i prove ent practices using Patterns in K.##. The organi@ation of each Pattern is as follows, initially the pro"le is descri"ed$ a solution for that pro"le is entioned and links to source code i ple entation for that pattern is given. (ote+, This Section assu es that reader has so e "asic knowledge of K.##. (ote., This Section does not focus on other advantages of Patterns such as flexi"le design$ reusa"ility etc. Service 2ocator Pro"lem3 K.## specification andates the usage of K(>I %Kava (a ing and >irectory Interface& to access different resources3services. K.## co pati"le server "inds these resources3services to the K(>I server so that the clients can lookup those resources3services through K(>I lookup process fro anywhere in the network. The resources3services can "e +. #K?Ho e o"jects .. >ataSource o"jects C. K*S !onnection-actory D. K*S Topic3Zueue etc. #K? !lient needs to initially get #K?Ho e o"ject fro K(>I to anage life cycle of #K?/"jects. K*S clients need to get !onnection-actory and Topic3Zueue fro K(>I for processing essages. K>?! clients need to get >ataSource o"ject in order to get data"ase connection. All these services need to "ind to the K(>I services and the clients need to lookup K(>I to get those services. !lients have to go through K(>I lookup process every ti e to work with these services. K(>I lookup process is expensive "ecause clients need to get network connection to the K(>I server if the K(>I server is located on a different achine and need to go through lookup process every ti e$ this is redundant and expensive. The figure "elow shows the clientLs K(>I lookup process.

Solution through Service 2ocator Pattern3 The solution for the redundant and expensive K(>I lookup process pro"le is to cache those service o"jects when the client perfor s K(>I lookup first ti e and reuse that service o"ject fro the cache second ti e onwards for other clients. This technique aintains a cache of service o"jects and looks up the K(>I only first ti e for a service o"ject. This technique reduces redundant and expensive K(>I lookup process thus increasing perfor ance significantly. Service Iocator Pattern i ple ents this technique "y having a class to cache service o"jects$ ethods for K(>I lookup and ethods for getting service o"jects fro the cache. The figure "elow shows the ServiceIocator class intercepting the client request and accessing K(>I once and only once for a service o"ject.

Here the clients call ServiceIocator class to get a service o"ject rather than calling K(>I directly. ServiceIocator acts as interceptor "etween client and K(>I. -or source code and different flavors of i ple entation of this Pattern$ see the following links. Source3 )ou can get the source for this Pattern in two flavors 1. Service Locator: Sun Kava !enter K.## Patterns catalog has this Pattern as Service Iocator %register and login to access this link&

http,33developer.java.sun.co 3developer3restricted3patterns3ServiceIocator.ht l 2. EJB Home Factory: TheServerSide.co has online #K? >esign Patterns "ook that has this Pattern as #K? Ho e -actory$ it is eant ainly for #K?Ho e o"jects %register and login to access this link&. http,33www.theserverside.co 3resources3patternsOreview.jsp Session ;acade Pro"lem3 #K? clients %swing$ servlets$ jsps etc& can access entity "eans directly. If #K? clients access entity "eans directly over the network$ it takes ore network calls and i poses network overhead. The following figure illustrates this process,

Here in the a"ove figure$ the servlet calls ultiple entity "eans directly to acco plish a "usiness process$ there"y increasing the nu "er of network calls. Solution through Session ;acade Pattern3 The solution for avoiding nu "er of network calls due to directly accessing ultiple entity "eans is to wrap entity "eans with session "ean %-acade&. The #K? client accesses session "ean %-acade& instead of entity "eans through coarse grained ethod call to acco plish a "usiness process. The following figure illustrates how the session facade %session "ean& acts as an interceptor "etween client and entity "eans,

Here the client akes only one coarse grained ethod call to session "ean %facade& to process a "usiness ethod instead of placing fine grained calls to entity "eans. The session "ean in turn calls entity "eans to process client request. #ntity "eans can "e ade local "y i ple enting #K?..M local interfaces to reduce re ote overhead "etween session facade and entity "eans. Therefore the session facade reduces the network traffic and increases perfor ance. Source3 )ou can get the source for this Pattern in 1. Session Facade: Sun Kava !enter K.## Patterns catalog has this Pattern as Session -acade %register and login to access this link& http,33developer.java.sun.co 3developer3restricted3patterns3Session-acade.ht l 2. Session Facade: TheServerSide.co has online #K? >esign Patterns "ook that has this Pattern as Session -acade %register and login to access this link&. http,33www.theserverside.co 3resources3patternsOreview.jsp 5essage ;acade Pro"lem3 Session "ean and entity "ean ethods execute synchronously that eans the ethod caller has to wait till a value is returned. In so e situations like sending hundredLs of ails or firing a "atch process or updating processes$ the client does not have to "other a"out return value. If you use synchronous session and entity "eans in such situations$ they take a long ti e to process ethods and clients have to wait till the ethod returns a value. The following figure illustrates how session "ean and entity "ean synchronously, ethods execute

The client has to wait till all the eight synchronous steps co plete. This synchronous execution takes a long ti e and has an i pact on perfor ance when the ethod process is huge. Solution through 5essage ;acade Pattern3 To avoid "locking of a client$ use asynchronous essage driven "eans$ so that client does not have to wait for a return value. If a client uses asynchronous essaging then the client need not wait for a return value "ut can continue its flow of execution after sending the essage. The following figure illustrates how a client sends a essage and how a essage facade %*essage driven "ean& processes essages asynchronously.

Here the client sends a essage to K*S server$ gets acknowledge ent fro the K*S server i ediately in two step process and continues itLs flow of execution. 7hereas K*S server delivers the essages to *essage driven "ean %*essage -acade& without "locking clientLs execution and *essage driven "ean executes essages. )ou can use nor al K*S consu ers instead of *essage driven "eans. This process i proves perfor ance "y reducing the clientLs "locking ti e considera"ly. Source3 )ou can get the source for this Pattern in two flavors

1. Service Activator: Sun Kava !enter K.## Patterns catalog has this Pattern as Service Activator %register and login to access this link& http,33developer.java.sun.co 3developer3restricted3patterns3ServiceActivator.ht l 2. Message Facade: TheServerSide.co has online #K? >esign Patterns "ook that has this Pattern as *essage -acade %register and login to access this link&. http,33www.theserverside.co 3resources3patternsOreview.jsp <alue O"&ect Pro"lem3 7hen a client calls a re ote ethod there will "e process of arshalling$ network calls and un arshalling involved for the re ote ethod invocation. If you choose fine grained approach when calling ethods re otely$ there will "e a significant network overhead involved. -or exa ple if you call fine grained ethod like this$ re ote/"ject.get(a e%&5 re ote/"ject.get!ity%&5 re ote/"ject.getState%&5 re ote/"ject.getVip!ode%&5 Here$ there are four network calls fro is re ote ethod call. client to the re ote o"ject "ecause every ethod call

The following figure illustrates the fine grained approach when calling

ethods re otely ,

As seen in the a"ove figure the fine grained approach i poses a overhead on the network due to the nu "er of calls. Solution through <alue O"&ect Pattern3 The solution for avoiding any network calls due to fine grained grained approach. -or exa ple , ethod calls is to use coarse

33 create an Ualue /"ject and fill that o"ject locally PersonInfo person 6 new PersonInfo%&5 person.set(a e%80avi8&5 person.set!ity%8Austin8&5 person.setState%8TW8&5 person.@ip!ode%8GHGDN8&5 33 send Ualue /"ject through network re ote/"ject.getPersonInfo%person&5 Here$ there is only one network call instead of three network calls and PersonInfo o"ject is a Ualue /"ject. The following figure illustrates the coarse grained approach that is passing a Ualue /"ject through network.

Ualue /"ject is an o"ject that is passed over the network rather than passing each attri"utes separately thus increasing perfor ance "y reducing network calls. Source3 )ou can get the source for this Pattern in 1.Va ue !"#ect: Sun Kava !enter K.## Patterns catalog has this Pattern as Ualue /"ject%register and login to access this link& http,33developer.java.sun.co 3developer3restricted3patterns3Ualue/"ject.ht l 2.Va ue !"#ect: TheServerSide.co has online #K? >esign Patterns "ook that has this Pattern as Ualue /"ject%register and login to access this link&. http,33www.theserverside.co 3resources3patternsOreview.jsp

<alueO"&ect;actory Pro"lem3 -or a single request$ a client ight need to access ultiple server side co ponents such as different session "eans and entity "eans. In such situations the client accesses ultiple co ponents over the network$ this increases the network traffic and has an i pact on the perfor ance. The following figure illustrates this pro"le ,

Solution through <alueO"&ect;acory Pattern3 To reduce the network traffic due to accessing ultiple co ponents "y a client for a single request$ let Ualue/"ject-actory hold different Ualue/"jects as place holders and respond with a single Ualue/"ject for a client request. Here Ualue/"ject-actory holds creation and delegation logic of Ualue/"jects for different client requests. The following figure illustrates how Ualue/"ject-actory intercepts client request and delegates to different co ponents to respond to a client request,

This Pattern reduces network calls and increases perfor ance. Source3 )ou can get the source for this Pattern in two flavors 1.Va ue !"#ect Assem" er: Sun Kava !enter K.## Patterns catalog has this Pattern as Ualue /"ject Asse "ler %register and login to access this link& http,33developer.java.sun.co 3developer3restricted3patterns3Ualue/"jectAsse "ler.ht l 2.Va ue !"#ect Factory: TheServerSide.co has online #K? >esign Patterns "ook that has this Pattern as Ualue /"ject -actory %register and login to access this link&. http,33www.theserverside.co 3resources3patternsOreview.jsp

<alue 2ist !andler Pro"lem3 K.## applications generally have the search facility and have to search huge data and retrieve results. If an application returns huge queried data to the client$ the client takes long ti e to retrieve that large data and If that application uses entity "ean to search data$ it has an i pact on perfor ance largely "ecause #K? "y nature has an overhead when co pared to nor al java o"ject %see !hoosing "etween #K? and nonJ#K? and #ntity "ean life cycle to know overhead involved with entity "eans&. This process has an i pact on perfor ance for two reasons$ +. Application returns large a ount of data to the client .. #ntity "eans are used to retrieve huge data. The following figure illustrates this process.

Solution through <alue 2ist !andler Pattern3

The solution to reduce overhead due to entity "eans and huge data "eing returned to the client is +. Ase >ata Access /"jects %>A/& rather than #ntity "eans .. 0eturn s all quantity of data data at once to the client. ultiple ti es iteratively rather than returning large a ount of

>ata Access /"ject encapsulates K>?! access logic. UalueIistHandler caches list of Ualue o"jects that are retrieved through >A/. 7hen client wants to search data$ It calls UalueIistHandler that is in turn responsi"le for caching data and returning data to the client iteratively. The following figure illustrates how Ualue Iist Handler intercepts client search request and returns data iteratively.

The Ualue Iist Handler Pattern i proves perfor ance significantly when the application searches huge data. Source3 )ou can get the source for this Pattern in Sun Kava !enter K.## Patterns catalog that has this Pattern as Ualue Iist Handler %register and login to access this link& http)**developer.$ava.sun.com*developer*restricted*patterns*+alue,istHandler.html

Composite -ntity Pro"lem3 #ntity "eans have ore overhead associated than a nor al java o"ject. See !hoosing "etween #K? vs nonJ#K? and #ntity "ean life cycle to know a"out overhead involed with entity "eans. #ntity "eans are not eant for representing every persistent o"ject in o"ject odel or ta"le in data"ase sche a. If you convert o"ject odel or data"ase sche a into entity "eans that has relationships %parentJchild&$ it will "e converted into fine grained entity "eans and any entity "eans will exist in your application. This approach i poses a lot of overhead on network and e ory resources. The following figure illustrates this fine grained entity "eans approach.

Solution through Composite -ntity Pattern3 The solution is ake coarse grained entity "eans that is to ake parent as entity "ean and children as nor al java o"jects. This coarse grained approach reduces inter entity "ean co unication and existence of nu "er of entity "ean in an application thus reducing overall network and e ory overhead that occur due to fine grained entity "eans. The following figure illustrates how !o posite #ntity "ean %parent "ean& contains nor al java o"jects %children& in relationship.

The !o posite #ntity Pattern i proves perfor ance significantly "y reducing nu "er of entity "eans in an application. Source3 )ou can get the source for this Pattern in Sun Kava !enter K.## Patterns catalog that has this Pattern as Aggregate #ntity Pattern %register and login to access this link& http)**developer.$ava.sun.com*developer*restricted*patterns*#ggregate-ntity.html

$ey Points +. Ase ServiceIocator3#K?Ho e-actory Pattern to reduce expensive K(>I lookup process. .. Ase Session-acade Pattern to avoid direct client access to #ntity "eans thus reducing network calls. C. Ase *essage-acade3ServiceActivator Pattern to avoid large ethod execution process. D. Ase Ualue/"ject Pattern to avoid fine grained ethod calls over network. E. Ase Ualue/"ject-actory3Ualue/"jectAsse "ler Pattern to avoid ultiple network calls for a single client request. F. Ase UalueIistHandler Pattern to avoid using #ntity "eans and send data iteratively to the client. G. Ase !o posite#ntity Pattern to avoid inter #ntity "ean overhead.

Overview of %5S
Kava *essage Service %K*S& is a Kava API to access *essageJ/rientedJ*iddle ware products %*/*& products. These */* products i ple ent K*S API so that java application can use K*S API in a vendor neutral anner. K*S clients co unicate with each other using essages$ this co unication occurs in an asynchronous anner$ that is when a sender sends a essage then it does not wait for the response "ut continues its flow of execution. There are two progra ing odels in K*S API +. Point to Point %PTP& .. Pu"lish and Su"scri"e %pu"JandJsu"& In PTP odel$ a essage is delivered to a single receiver only while in pu"JandJsu" a essage is "roadcasted to ultiple receivers. The following are the "asic steps to write a K*S progra +. I port javax.j s package .. Iookup !onnection-actory C. !reate !onnection D. !reate Session E. Iookup >estination %Topic or Zueue& F. !reate Producers and !onsu ers G. !reate *essage H. Send and receive *essages 7e will look at these areas one "y one$ how to opti i@e !onnection$ Session$ >estination$ Producer3!onsu er$ *essage$ and finally we will have a look at other opti i@ation techniques to i prove perfor ance in K*S. (ote, This Section assu es that reader has so e "asic knowledge of K*S. Optimization with Connection A connection represents an open connection %T!P3IP& fro the K*S client to the K*S server. !onnection is used to create Session o"jects that in turn create essage producers and consu ers.

A !onnection o"ject is created "y !onnection-actory that could either "e a Topic!onnection or a Zueue!onnection. 7hen you create and use a !onnection$ consider the following opti i@ation techniques , +. Start the !onnection when appropriate .. Process essages concurrently C. !lose the !onnection when finished +6 Start the Connection when appropriate )ou need to start a !onnection using the start%& ethod to start allowing the flow of essages fro the producer to the K*S server. 7hen do you start the !onnectionT If you start a connection "efore starting the su"scri"er30eceiver %consu er& then the essages have to wait in the K*S server or they persist if they are dura"le essages$ this is an unnecessary overhead so to avoid this $first start !onsu ers and then start the Producer !onnection. ,6 Process messages concurrently K*S provides a facility to process essages concurrently "y getting a !onnection!onsu er that uses server session pool. The server session pool is a pool of Sessions$ each one executes separate essage concurrently. This facility gives an application a"ility to process essages concurrently thus i proving perfor ance. )ou can create !onnection!onsu er using these -or Zueues , pu"lic !onnection!onsu er create!onnection!onsu er%Zueue queue$ String essageSelector$ ethods.

ServerSessionPool sessionPool$ int -or Topics , ax*essages& throws K*S#xception

pu"lic !onnection!onsu er create!onnection!onsu er%Topic topic$ String essageSelector$

ServerSessionPool sessionPool$ int ax*essages& throws K*S#xception

In these ethods the ain para eters are ax*essages and ServerSessionPool. ax*essages denote the axi u nu "er of essages that can "e si ultaneously assigned to a server session. ServerSessionPool is an ad inistered o"ject that you configure in vendor specific anner. This process works si ilar to *essage driven "eans where you can process ultiple essages concurrently. This gives good perfor ance and scala"ility. So e of the K*S vendors support this facility$ "ut so e vendors donLt. So see your K*S server docu entation for detailed infor ation . 76 Close the Connection when finished )ou need to close the external resources like network or a data"ase connection explicitly as soon as you are done with the . Si ilarly a K*S connection is also a T!P3IP connection to the K*S server $ you need to close the !onnection using the close%& ethod as and when you

finish your work $so that when you close the !onnection it closes itLs Session and Producer3!onsu er o"jects also. Optimization with Session A Session is used to create ultiple producers and consu ers. A Session can "e a ZueueSession for a PTP or a TopicSession for a pu"JandJsu" odel. 7hen you create a Session o"ject$ consider the following opti i@ation techniques to i prove perfor ance. +. !hoose proper acknowledge ent .. !ontrol Transaction C. !lose the Session when finished. +6 Choose proper ac*nowledgement mode 7hen you create a Session o"ject$ you can choose anyone of the three acknowledge ent odes$ AAT/OA!Y(/7I#>'#$ !II#(TOA!Y(/7I#>'# or >APSO/YOA!Y(/7I#>'#. -or exa ple$ -or Topic, topicSession6topic!onnect.createTopicSession%false$ Session.!II#(TOA!Y(/7I#>'#&5 -or Zueue, qsession6queue!onnect.createZueueSession%false$ session.AAT/OA!Y(/7I#>'#&5 Here you have a choice of choosing an acknowledge ent a ong three odes. #ach of these odes has a specific functionality. As per perfor ance perspective$ which ode gives the "est perfor anceT !II#(TOA!Y(/7I#>'# ode is not a feasi"le option %when you have the freedo to choose fro the other two options& since the K*S server cannot send su"sequent essages till it receives an acknowledge ent fro the client. AAT/OA!Y(/7I#>'# ode follows the policy of delivering the essage onceJandJonly once "ut this incurs an overhead on the server to aintain this policy . >APSO/YOA!Y(/7I#>'# ode has a different policy of sending the essage ore than once there"y reducing the overhead on the server %i posed when using the AAT/OA!Y(/7I#>'#& "ut i poses an overhead on the network traffic "y sending the essage ore than once. ?ut the AAT/OA!Y(/7I#>'# ode cleans up resources early fro the persistent storage3 e ory which reduces the overhead "ecause of that. In su ary$ AAT/OA!Y(/7I#>'# or >APSO/YOA!Y(/7I#>'# give "etter perfor ance than !II#(TOA!Y(/7I#>'#. ,6 Control #ransaction In K*S a transaction is a group of essages that are consu ed3delivered in allJorJnone fashion. )ou ake essages as transactional essages "y giving LtrueL flag when creating a session. topicSession 6 t!onnect.createTopicSession%true$Session.AAT/OA!Y(/7I#>'#&5 queueSession 6 q!onnect.createZueueSession%true$Session.AAT/OA!Y(/7I#>'#&5 In the a"ove code the first para eter indicates the session as transactional session. Session has co it%&$ roll"ack%& and isTransacted%& ethods to deal with transactional essages. The pro"le here is that a transaction starts i plicitly when session is created and ends when ode

co it%& or roll"ack%& ethod is called. At this stage$ after calling co it%& or roll"ack%& ethod$ one ore transaction starts i plicitly "ecause there is no explicit ethod %"egin%& ethod& to start a transaction . So there are a chain of transactions that depend upon co it%& or roll"ack%& ethod calls. Transactional essages are cu ulated at K*S server until the transaction is co itted or rolled"ack this i poses significant overhead on K*S server. Suppose if you want to send +MM essages$ out of which you want only +M to essages in a transaction$ How would you control transaction in such situationsT The "est ethod is to divide transactional essages and nonJtransactional essages separately. !reate transactional session for transactional essages "y giving LtrueL flag %see code a"ove& and create a separate nonJtransactional session for nonJtransactional essages "y giving LfalseL flag. This way$ you can control transaction in order to i prove perfor ance. 76 Close the Session when finished It is always "etter to re ove an o"ject as early as possi"le when finished with $although closing a connection class closes session$ this allows the gar"age collector to re ove o"jects earlier. Optimization with estination >estination %Topic3Zueue& is a virtual channel "etween producers and consu ers. Producers send essages to the >estination which in turn deliver essages to consu ers. >estination encapsulates the vendor specific na e. >estination %Topic3Zueue& is configured in a vendor specific para eters can "e configured , +. *axi u si@e of the >estination .. *axi u nu "er of essages in the >estination C. Priority of essages D. Ti e to live E. Ti e to deliver F. >elivery ode G. 0edelivery delay H. 0edelivery li it 7e need to look up K(>I to get >estination o"ject. Initial!ontext ic 6 new Initial!ontext%properties&5 Topic topic 6 %Topic& ic.lookup%topic(a e&5 Zueue queue 6 %Zueue& ic.lookup%queue(a e&5 All the a"ove configura"le para eters have an i pact on the perfor ance. Here we will discuss the si@e of >estination$ axi u essages in the >estination$ 0edelivery delay and 0edelivery li it. -or nonJdura"le essages$ the ti e that essages take to deliver to the >estination depends upon its nu "er and >estination si@e. If a large nu "er of essages collect in a >estination$ they take ore ti e to deliver. So give less >estination si@e and less nu "er of axi u essages to the >estination to i prove perfor ance. 0edelivery delay ti e defines when to redeliver a essage if a failure occurs. If this is less$ the frequency of redelivery of a essage is high thus increasing network traffic and vice versa. So high 0edelivery delay ti e gives "etter perfor ance. 0edelivery Ii it defines the nu "er of ti es a essage should "e redelivered. Although the pro"a"ility of guaranteed essaging is less$ if the 0edelivery li it is less$ then the perfor ance is "etter "ecause the e ory anner$ The following

overhead for non dura"le essages and persistent overhead for dura"le reduced.So set opti al 0edelivery li it to i prove perfor ance. Optimization with 5essage Producer=Consumer

essages is

Producer%Sender3Pu"lisher& sends essages to the >estination%Zueue3Topic& where as !onsu er%0eceiver3Su"scri"er& consu es essages fro the >estination. *essage Producer3!onsu er is created "y Session o"ject. -or Topics, TopicPu"lisher pu"lisher 6 pu"Session.createPu"lisher%topic&5 TopicSu"scri"er su"scri"er 6 su"Session.createSu"scri"er%topic&5 -or Zueues, ZueueSender sender 6 sendSession.createSender%queue&5 Zueue0eceiver receiver 6 receiverSession.create0eceiver%queue&5 you send the -or Topics, pu"lisher.pu"lish%*essage essage&5 or essage$ int delivery*ode$ int priority$ long essages using Producer$

pu"lisher.pu"lish%Topic topic$ *essage ti eToIive&5

-or Zueues, sender.send%*essage essage&5 or essage$ int delivery*ode$ int priority$ long

sender.send%Zueue queue$ *essage ti eToIive&5

The para eters >elivery*ode and Ti eToIive are i portant fro perfor ance perspective. )ou can give values for these para eters when you configure !onnection-actory or >estination or when you send a essage %see a"ove&. 7hen you send the essage using send%& ethod or when you configure the delivery ode and ti eToIive para eters in !onnection-actory or >estination$ consider the following opti i@ation techniques to i prove perfor ance. +. !hoose nonJdura"le essages where appropriate

.. Set Ti eToIive value properly C. 0eceive essages asynchronously

D. !lose Producer3!onsu er when finished +6 Choose non.dura"le messages where appropriate >elivery ode defines whether the essage can "e dura"le3persistent or nonJdura"le3nonJ persistent$ this factor has an i pact on the perfor ance. This para eter ensures that essage delivery is guaranteed. -or dura"le essages the delivery ode value is >elivery ode.P#0SIST#(T$ for nonJdura"le essages delivery ode value is >elivery ode.(/(OP#0SIST#(T. If you define the delivery ode as dura"le then the essage is stored "y the K*S server "efore delivering it to the consu er. The following figure illustrates this process.

If you define the delivery ode as nonJdura"le then the essage is delivered to the consu er without "eing saved "y the K*S server. The following figure illustrates this.

The a"ove figures clearly show the difference "etween the two delivery odes. 7hen using the dura"le delivery ode$ each essage has to "e stored "y the K*S server either in the data"ase or the file syste depending on the vendor "efore delivery of essage to consu er and re oved after delivery of essage. This has a huge i pact on the perfor ance. So as far as possi"le restrict the use of dura"le delivery ode unless and until a"solutely necessary for your application to avoid the overheads involved. ,6 Set #ime#o2ive value properly )ou can set the age of the essage "y setting the Ti eOToOIive para eter after which the essage expires. ?y default the essage never expires $set opti al essage age so as to reduce e ory overhead$ thus i proving perfor ance. 76 0eceive messages asynchronously )ou can receive essages synchronously or asynchronously. -or recieving asynchronous essages you need to i ple ent the *essageIistener interface and on*essage%& ethod.

-or receiving synchronous *essage!onsu er , receive%&5 receive%long ti eout&5 receive(o7ait%&5

essages you need to use anyone of the following

ethods of

The first ethod "locks the call until it receives the next essage$ the second ethod "locks till a ti eout occurs and the last ethod never "locks . 7hen using asynchronous essaging the calls are never "locked so it is a "etter option to receive essages asynchronously "y i ple enting *essageIistener to i prove perfor ance. 86 Close Producer=Consumer when finished It is always "etter to re ove an o"ject as early as possi"le when finished with$ although closing a connection class closes session and Producer3!onsu er$ this allows the gar"age collector to re ove o"jects earlier.

Optimization with 5essage A *essage o"ject contains infor ation that is passed "etween applications. It contains infor ation as payload$ headers and properties. As per perfor ance perspective$ you need to ainly consider the type of essage J Text$ /"ject $?yte $ Strea or *ap essage. The essage si@e depends on the type of essage you choose which in turn has an i pact on the perfor ance. Iess si@e gives "etter perfor ance and vice versa. -or exa ple$ ?yte*essage takes less e ory than Text*essage. /"ject*essage carries a seriali@ed java o"ject$ when you choose /"ject*essage you need to use LtransientL keyword for varia"les that need not "e sent over the network to reduce overhead. See Seriali@ation for detailed infor ation. In su ary choose essage type carefully to avoid unnecessary e ory overhead.

Choosing right %5S server !hoosing the right K*S server for "est perfor ance ight "e a difficult task since every vendor clai s that their server is the "est server. Here are a few links which have the "ench arks of various servers. Sonic softwareLs K*S server Sonic*Z "ench arks$ a "ench ark co parison "etween Sonic*Z and -iorano*Z K*S servers. http,33www.sonicsoftware.co 3whiteOpapers3fiorano.pdf -ioranoLs K*S server -iorano*Z "ench arks$ a "ench ark co parison "etween -iorano*Z and Sonic*Z K*S servers. http,33www.fiorano.co 3products3perfor anceOco parison.ht

After seeing the "ench arks it ay indeed "e confusing for you to decide on a particular server $ "ut here are a few points for your own "ench ark testing and choosing a K*S server. +. The type of essage odel you want to use in your odel either PTP or pu"JandJsu" or a co "ination of "oth. .. The volu e of essages and the rate of essage flow % essages per second&.

C. D. E. F. G. H.

The nu "er of applications involved. The essage type and si@e The essage delivery ode J dura"le3nonJdura"le The nu "er of connections to "e opened. Uendor specific opti i@ation features Support for clustering$ which gives good scala"ility.

The a"ove entioned points can "e looked into when choosing a K*S server for your application.

$ey Points +. Start producer connection after you start consu er. .. Ase concurrent processing of essages. C. !lose the !onnection when finished. D. !hoose either >APSO/YOA!Y(/7I#>'# or AAT/OA!Y(/7I#>'# rather than !II#(TOA!Y(/7I#>'#. E. !ontrol transactions "y using separate transactional session for transactional essages and nonJtransactional session for nonJtransactional essages. F. !lose session o"ject when finished. G. *ake >estination with less capacity and send essages accordingly. H. Set high 0edelivery delay ti e to reduce network traffic. N. Set less 0edelivery li it for reducing nu "er of essage hits. +M. !hoose nonJdura"le essages wherever appropriate to avoid persistence overhead. ++. Set opti al essage age %Ti eToIive value&. +.. 0eceive essages asynchronously. +C. !lose Producer3!onsu er when finished. +D. !hoose essage type carefully to avoid unnecessary e ory overhead. +E. Ase LtransientL key word for varia"les of /"ject*essage which need not "e transferred.

Performance 'mprovement techniques in Collections


This topic illustrates the perfor ance i prove ent techniques in !ollections with the following sections, /verview of !ollections /pti i@ation techniques in Iists /pti i@ation techniques in Sets /pti i@ation techniques in *aps Yey Points Overview of Collections !ollection is a group of o"jects. java.util package provides i portant types of collections. There are two funda ental types of collections they are !ollection and *ap. !ollection types

hold a group of o"jects$ #g. Iists and Sets where as *ap types hold group of o"jects as key$ value pairs #g. Hash*ap and Hashta"le. This section exa ples are tested on 7indows .MMM$ K>Y+.... illenniu $ C.M " 0A*$ K>Y +.C and

(ote, This section assu es that reader has so e "asic knowledge of Kava !ollections. Optimization techniques in 2ists Iist types represent an ordered collection of o"jects. ArrayIist$ Uector$ Stack and IinkedIist are the Iist i ple entation classes. All Iist types support "asic operations J adding o"jects$ re oving o"jects$ accessing o"jects and iterating through the list. So which one to choose since all the list i ple entations support these "asic operationsT Perfor ance is different for each class "ased on specific operations. So your choice is driven "y the perfor ance and the require ent options. )our require ent could "e +. Thread safe collection .. Si@e of collection %large or s all collection& C. Type of operation % adding$ re oving$ accessing or iterating & If you want your collection to "e thread safe then Uector or Stack ust "e used "ecause "oth have synchroni@ed ethods. 7hile ArrayIist and IinkedIist are not thread safe. Stack is eant for specific II-/ %last in J first out& operations$ this can "e filtered down "ased on this specific require ent. If you donLt want your collection to "e thread safe then you have can choose "etween ArrayIist or IinkedIist. 'eneral concept fro perfor ance point of view is that ArrayIist gives "etter perfor ance when accessing and iterating o"jects whereas IinkedIist gives "etter perfor ance when adding and re oving o"jects. Although true in ost cases$ so eti es there is an exception. The following are the "ench arks shown for each operation separately. >dding o"&ects3 The ta"le "elow shows ti e taken when I run IistAddTest.java which adds ele ents at different positions and is run on different K>Y versions to easure perfor ance "ench arks. Ti e shown here is in illi seconds. ArrayIist ArrayIist Uector with Si@e of K>Y Uector with Type of operation with out with out IinkedIist collection version initiali@ation initiali@ation initiali@ation initiali@ation +.. +NE +E CM .E CNM Adding o"jects at end +.C GM +M FM .M EM +.. .DHH .E+C .EGH .EMH +F.D+C EMMMM Adding o"jects at o"jects iddle +.C .EDC .EEC .F+N .EGD NFEEC +.. EECH FMEC EDG. HCGG DE Adding o"jects at first +.C FDNN EHDH EEFH FMGH CM Adding o"jects at end+.. .+E CE GM FM C.E +MMMM Adding o"jects at +.. +++N+ ++D+F ++MM+ +MHGE FF.+G. o"jects iddle Adding o"jects at first +.. ++EHG+ ++NNF. ++HHC+ +.M.NC HE

conclusion is

Type of operation

Uector with out Uector with IinkedIist initiali@ation initiali@ation fast %"ut sligtly slower than fast%"ut sligtly fast % "ut slightly fast %"ut slower initiali@ation and slower than Adding o"jects slower than than fast slower than ArrayIist at end ArrayIist and initiali@ation& ArrayIist "ecause of Uector& "ecause of synchroni@ation& synchroni@ation& slow % slower slow % slower slow % slower slow % slower worse% worse Adding o"jects than when than when than when than when than every at iddle adding o"jects adding o"jects adding o"jects adding o"jects operation& at last& at last& at last& at last& slow % slower slow % slower slow % slower slow % slower slow % slower than when than when than when than when than when Adding o"jects adding o"jects adding o"jects adding o"jects adding o"jects adding o"jects at first at last and at last and at last and at last and at last and iddle& iddle& iddle& iddle& iddle&

ArrayIist with ArrayIist with out initiali@ation initiali@ation

The reason is +. K>Y +.C gives "est perfor ance "ecause of HotSpot Uirtual *achine. .. The initial si@e for ArrayIist and Uector is +M. ArrayIist increases its capacity "y half approxi ately whenever its capacity reaches axi u %+M& "ut Uector increases its capacity "y dou"le whenever its capacity reaches axi u . That is the reason why ArrayIist takes ore ti e than Uector if it is not initiali@ed with proper si@e though ArrayIist is not synchroni@ed. As soon as it reaches its axi u capacity when adding o"jects$ it creates one ore "igger array % with +E capacity for ArrayIist approxi ately and .M capacity for Uector& and copies the previous and new o"jects into new array. /"viously it is expensive to create new array and copy o"jects. So "est approach is to initiali@e the ArrayIist and Uector with proper si@e using constructors or using ensure!apacity%int capacity& which gives good perfor ance. If you initiali@e with proper si@e then the ArrayIist gives "etter perfor ance than Uector. ArrayIist with initiali@ation gives "etter perfor ance than others "ecause its ethods are nonJ synchroni@ed. Synchroni@ed ethods are "it expensive "ecause KU* has to lock the o"jects whenever it finds synchroni@ed ethods. Uector takes slightly ore ti e than ArrayIist when you use K>Y+.C Hotspot KU* $if you are not sure that whether your collection needs to "e thread safe or not then it is "etter to use Uector to have higher safety. )ou can convert an ArrayIist as thread safe collection using !ollections.synchroni@edIist%ArrayIist o"ject& "ut it is ore expensive than using a Uector.

C. ArrayIist and Uector aintain internal /"ject array % /"ject<=& to store o"jects. So whenever you add an o"ject$ they add it to the end of the array which is fine as long as it doesnLt reach its axi u capacity. If you want to add an o"ject at any other position$ it creates a new o"ject array and recopies all the o"jects which is expensive. That is the reason why adding o"jects at iddle and "eginning of collection takes a long ti e than when it is adding at the end.

D. IinkedIist gives good perfor ance when adding ele ents at the end and "eginning "ut it is worse when adding o"jects at iddle "ecause it needs to scan the node whenever it needs to add an o"ject. IinkedIist cannot "e initiali@ed. The constructors for ArrayIist and Uector to initiali@e with proper si@e are ArrayIist% int initialcapacity& Uector% int initialcapacity& Uector% int initialcapacity$ int capacityIncre ent& )ou can give incre ental capacity in Uector to change the default incre ent in capacity. Here is the IistAddTest.java source code. package co .perfor ance.util5 33This class gives the Iist classes "ench arks for adding o"jects at end$ iddle and first i port java.util.Iist5 i port java.util.ArrayIist5 i port java.util.IinkedIist5 i port java.util.Uector5 pu"lic class IistAddTest 1 private static final int (A* 6 EMMMM5 private static String<= o"js 6 null5 pu"lic void addIast%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.add%o"js<i=&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for adding /"jects at #nd, 8 B %endTi e J startTi e& &5 ;

pu"lic void add-irst%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.add%M$o"js<i=&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for adding /"jects at -irst , 8 B %endTi e J startTi e& &5 ; pu"lic void add*iddle%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.add%i3.$o"js<i=&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for adding /"jects at *iddle , 8 B %endTi e J startTi e& &5 ; pu"lic void doTest%Iist list& 1 addIast%list&5 clear%list&5 add*iddle%list&5 clear%list&5 add-irst%list&5

clear%list&5 ; pu"lic void clear%Iist col&1 if%Rcol.is# pty%&& col.clear%&5 ; pu"lic static void ain%String<= args&1

o"js 6 new String<(A*=5 for%int i6M5i9(A*5iBB&1 o"js<i= 6 8/"ject8Bi5 ; IistAddTest col 6 new IistAddTest%&5 ArrayIist collection+ 6 new ArrayIist%&5 col.doTest%collection+&5 ArrayIist collection+A 6 new ArrayIist%(A*&5 col.doTest%collection+A&5 Uector collection. 6 new Uector%&5 col.doTest%collection.&5 Uector collection.A 6 new Uector%(A*&5 col.doTest%collection.A&5 IinkedIist collectionD 6 new IinkedIist%&5 col.doTest%collectionD&5 ; ;

0emoving o"&ects3 The ta"le "elow shows ti e taken when I run Iist0e oveTest.java on re oving ele ents fro different positions to easure perfor ance "ench arks. Ti e shown here is in illiseconds. Si@e of collection K>Y Type of operation version 0e oving o"jects fro end 0e oving o"jects fro iddle 0e oving o"jects fro first 0e oving o"jects fro end 0e oving o"jects fro +.C iddle 0e oving o"jects fro first 0e oving o"jects fro end 0e oving o"jects fro iddle 0e oving o"jects fro first

ArrayIist M CGM F+E FM +H+M F+EE +E ED.G CMH.G

Uector EM CM. F+G EM +H+M EHF. E. ENG. CFCGM

IinkedIist +. ..DM M +E DFHEM M M +CNNE. .G

.MMMM o"jects

EMMMM o"jects

HMMMM o"jects

The conclusion for re oving o"jects is +. All classes take approxi ately sa e ti e when re oving o"jects fro end .. ArrayIist and Uector give si ilar perfor ance with slight difference "ecause of K>Y+.C Hotspot KU*. C. IinkedIist gives worst perfor ance when re oving o"jects fro iddle %si ilar to adding o"jects at iddle&. D. IinkedIist gives "etter perfor ance when re oving o"jects fro the "eginning. E. /nly IinkedIist gives "etter perfor ance when re oving o"jects fro the "eginning. Here is the Iist0e oveTest.java source code package co .perfor ance.util5 33 This class shows the "ench arks of Iist types for re oving o"jects at end$ and first i port java.util.Iist5 i port java.util.ArrayIist5 i port java.util.IinkedIist5 iddle

i port java.util.Uector5 i port java.util.Arrays5 pu"lic class Iist0e oveTest 1 private static final int (A* 6 .MMMM5 private static /"ject<= o"js 6 null5 pu"lic void re oveIast%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6(A*5i:M5iJJ&1 list.re ove%iJ+&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for re oving /"jects at #nd, 8 B %endTi e J startTi e& &5 ; pu"lic void re ove-irst%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.re ove%M&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for re oving /"jects at -irst , 8 B %endTi e J startTi e& &5 ; pu"lic void re ove*iddle%Iist list& 1

long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.re ove%%(A*Ji&3.&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for re oving /"jects at *iddle , 8 B %endTi e J startTi e& &5 ; pu"lic void doTest%Iist collection& 1 collection.addAll%getIist%&&5 33 fill the Iist re oveIast%collection&5 clear%collection&5 collection.addAll%getIist%&&5 33 fill the Iist re ove*iddle%collection&5 clear%collection&5 collection.addAll%getIist%&&5 33 fill the Iist re ove-irst%collection&5 clear%collection&5 ; pu"lic void clear%Iist col&1 if%Rcol.is# pty%&& col.clear%&5 ; pu"lic Iist getIist%&1

o"js 6 new /"ject<(A*=5 for%int i6M5i9(A*5iBB&1 o"js<i= 6 new /"ject%&5 ; return Arrays.asIist%o"js&5 ; pu"lic static void ain%String<= args&1

Iist0e oveTest col 6 new Iist0e oveTest%&5 ArrayIist collection+ 6 new ArrayIist%&5 col.doTest%collection+&5 Uector collection. 6 new Uector%&5 col.doTest%collection.&5 IinkedIist collectionD 6 new IinkedIist%&5 col.doTest%collectionD&5 ; ;

>ccessing o"&ects3 The ta"le "elow shows ti e taken when I run IistAccessTest.java for accessing ele nts at different positions to easure perfor ance "ench arks. Ti e shown here is in illiseconds. Si@e of collection K>Y Type of operation version +.C Accessing o"jects fro end Accessing o"jects fro iddle Accessing o"jects fro first Accessing o"jects fro end

ArrayIist M M M M

Uector M M M DE

IinkedIist DGM+ .+MM. +E DE+MM

.EMMM o"jects

EMMMM o"jects

+MMMMM o"jects

Accessing o"jects fro iddle Accessing o"jects fro first Accessing o"jects fro end Accessing o"jects fro iddle Accessing o"jects fro first

M M M M M

M .M EM CM M

++.+MM +E .++HEM DEGMNM +E

The conclusion is +. ArrayIist and Uector give "est perfor ance "ecause they access o"jects using index. Uector takes slightly ore ti e "ut it is negligi"le. .. IinkedIist gives worst perfor ance when accessing o"jects at end and iddle "ecause it has to scan nodes to access o"jects. Here is the IistAccessTest.java source code package co .perfor ance.util5 33 This class shows the "ench arks of Iist types for accessing o"jects at end$ and first i port java.util.Iist5 i port java.util.ArrayIist5 i port java.util.IinkedIist5 i port java.util.Uector5 i port java.util.Arrays5 pu"lic class IistAccessTest 1 private static final int (A* 6 .EMMM5 private static /"ject<= o"js 6 null5 pu"lic void get-ro Iast%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6(A*5i:M5iJJ&1 list.get%iJ+&5 ; iddle

long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for getting /"jects at Iast, 8 B %endTi e J startTi e& &5 ; pu"lic void get-ro -irst%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.get%M&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for getting /"jects at -irst , 8 B %endTi e J startTi e& &5 ; pu"lic void get-ro *iddle%Iist list& 1 long startTi e 6 Syste .currentTi e*illis%&5 for%int i6M5i9(A*5iBB&1 list.get%(A*3.&5 ; long endTi e 6 Syste .currentTi e*illis%&5 Syste .out.println%8Ti e taken for getting /"jects at *iddle , 8 B %endTi e J startTi e& &5 ; pu"lic void doTest%Iist list& 1 list.addAll%getIist%&&5

get-ro Iast%list&5 get-ro *iddle%list&5 get-ro -irst%list&5 ; pu"lic void clear%Iist col&1 if%Rcol.is# pty%&& col.clear%&5 ; pu"lic static Iist getIist%&1 o"js 6 new /"ject<(A*=5 for%int i6M5i9(A*5iBB&1 o"js<i= 6 new /"ject%&5 ; return Arrays.asIist%o"js&5 ; pu"lic static void ain%String<= args&1

IistAccessTest col 6 new IistAccessTest%&5 ArrayIist collection+ 6 new ArrayIist%&5 col.doTest%collection+&5 Uector collection. 6 new Uector%&5 col.doTest%collection.&5 IinkedIist collectionD 6 new IinkedIist%&5 col.doTest%collectionD&5 ; ;

'terating collection3 Iterating collection using all three types of classes $ArrayIist $Uector and IinkedIist gives si ilar perfor ance "ecause they need not do any extra work they si ply iterate one "y one. So I did not give any "ench ark results. )ou can use any Iterator . ?ut using IistIterator gives ore flexi"ility than Iterator and #nu eration. )ou can traverse "oth sides Optimization techniques in Sets Set is a collection of unique o"jects$ it doesnLt allow duplicate o"jects and odification of existing o"jects. Set types also allow "asic operations like adding o"jects$ re oving o"jects$ accessing o"jects$ iterating o"jects "ut do not allow odification. There are two i ple entations of the Set interface they are HashSet and TreeSet. HashSet gives "etter perfor ance than TreeSet "ecause $ TreeSet is an ordered collection of o"jects and the o"jects are sorted while they are inserted in the TreeSet where as in case of HashSet o"jects are added in an adhoc anner. It is expensive to do all "asic operations in TreeSet "ecause it has to co pare and sort every o"ject. 7e can get "etter perfor ance "y using a HashSet and converting it to a TreeSet later on. HashSet and TreeSet are "acked "y Hash*ap and Tree*ap respectively. 7henever we use a HashSet we can specify an initial capacity and load factor using constructors. The default si@e for a HashSet is ++ and itLs load factor is M.GE. Ioad factor deter ines at which capacity HashSet has to "e resi@ed. ItLs internal structure will "eco e dou"le in si@e when it reaches itLs axi u capacity "ased on load factor. HashSet scales well when it is initiali@ed with proper si@e and default load factor. 7hen you know the the nu "er of o"jects to "e added$ it is "etter to initiali@e with that capacity and put load factor as +.Mf. The o"jects in HashSet are stored and retrieved through hash code which provides constant look up ti e. I did not give any "ench arks for these two Sets "ecause 7e donLt have any options here to co pare and evaluate. 7e have two Sets to choose. Ase TreeSet if you want sorted collection otherwise use HashSet. The constructors for the HashSet to initiali@e with proper si@e are, HashSet%int initialcapacity& HashSet%int initialcapacity$ float loadfactor&

Optimization techniques in 5aps


*ap is a collection of key and value o"ject associations. )ou can do all "asic operations as in Iists and Sets such as adding $ re oving $and accessing keyJvalue pairs. There are four types of *ap i ple entations they are Hash*ap$ Hashta"le$ 7eakHash*ap and Tree*ap. Hash*ap$ Hashta"le and 7eakHash*ap have si ilar i ple entations. Tree*ap is eant for sorted collection$ this can "e filtered down "ased on the require ent. Then we have other three types to choose fro . The choice again depends upon your require ent. )our require ent could "e +. Thread safe .. Type of operation % "asic operations & Hash*ap and 7eakHash*ap are not synchroni@ed whereas Hashta"le is synchroni@ed. 7eakHash*ap is a special purpose ap which uses an internal hashta"le. 7hen there are no ore references to key o"ject except weak reference aintained "y 7eakHash*ap$ the gar"age collector reclai s the key o"ject and apping "etween key o"ject and value o"ject is

also reclai ed$ if the value o"ject does not have any other references then the value o"ject is also reclai ed "y the gar"age collector. If you want your *ap type collection to "e thread safe$ then you need to use Hashta"le otherwise use Hash*ap. Hash*ap gives "etter perfor ance than Hashta"le "ecause of itLs nonJsynchroni@ed ethods. The reason I did not give any "ench arks for *ap types is that it is pretty straight forward to choose *ap type depending on require ent . )ou can i prove perfor ance "y using proper initial si@e and load factor in the constructor for all types of *ap types except Tree*ap. The constructors are Hash*ap%int initialcapacity& Hash*ap%int initialcapacity$ float loadfactor& Hashta"le%int initialcapacity& Hashta"le%int initialcapacity$ float loadfactor& 7eakHash*ap%int initialcapacity& 7eakHash*ap%int initialcapacity$ float loadfactor& 7hen the nu "er of o"jects exceed loadfactor capacity$ then the capacity of the class increases to %.Xcapacity B +&. The default load factor is M.GE. All these classes work in accordance with hash values which are used to identify the value o"jects. The key o"jects are converted to integer called hash code "y using hashing algorith s which is used as an index for value o"jects. Hash code ust "e sa e for two equal o"jects$ i.e. when tested with the equals%& ethod$it ust return true. The hash code is deter ined "y using hash!ode%& ethod. The hash code of a collection is deter ined "y cu ulating all the hash codes of the associated o"jects.

$ey Points 2ists3 .. Ase ArrayIist with proper initiali@ation if you donLt want thread safe for the collection whenever you add3re ove3access o"jects at end and iddle of collection. /. Ase Uector with proper initiali@ation if you want thread safe for the collection whenever you add3re ove3access o"jects at end and iddle of collection. 0. Ase IinkedIist if you donLt want thread safe for the collection whenever you add3re ove3access o"jects at "eginning of collection. 1. Ase synchroni@ed IinkedIist if you want thread safe for the collection whenever you add3re ove3access o"jects at "eginning of collection. 2. Ase IistIterator than Iterator and #nu eration for Iist types Sets3 .. Ase HashSet for aintaining unique o"jects if you donLt want thread safe for the collection for all "asic%add3re ove3access& operations otherwise use synchroni@ed HashSet for thread safe. /. Ase TreeSet for ordered and sorted set of unique o"jects for nonJthread safe collection otherwise use synchroni@ed TreeSet for thread safe 5aps3 .. Ase Hash*ap for nonJthread safe

ap collection otherwise use Hashta"le for thread safe

collection. /. Ase Tree*ap for nonJthread safe ordered Tree*ap for thread safe. ap collection otherwise use synchroni@ed

You might also like