You are on page 1of 13

Guide to JDBC Performance Tuning

(made by: Hitesh Wadhwa email: hwadhwa@csc.com)

What am I going to cover in this doc:

Recently, I had to implement a JDBC program in my project. The task wasn't simple, b t to gi!e yo an o!er!iew, it in!ol!ed copying million o" records "rom one DB table to another DB table. Beca se the DB machines were di""erent, and the data was h ge, it sed to take many ho rs #almost a day$ to trans"er the data. %o I had to work on per"ormance t ning the JDBC program, so that the data trans"er doesn't take more than &'(') min tes. *orking on this task, I ended p researching a lot on JDBC and its per"ormance t ning. I hope this doc ment pro!es to be o" immense help to others.

Overview of JDBC:

JDBC de"ines how a Ja!a program can comm nicate with a database. JDBC architect re de"ines di""erent layers to work with any database and ja!a, they are JDBC +,I inter"aces and classes which are at top most layer# to work with ja!a $, a dri!er which is at middle layer #implements the JDBC +,I inter"aces that maps ja!a to database speci"ic lang age$ and a database which is at the bottom #to store physical data$ JDBC pro!ides inter"aces and classes to work with databases. (- Connection inter"ace . It encaps lates the database connection " nctionality. (- %tatement inter"ace . It encaps lates %/0 1 ery representation and e2ec tion " nctionality. (- Res lt%et. This inter"ace encaps lates retrie!ing data which comes "rom e2ec tion o" %/0 1 ery sing %tatement. The "ollowing are the basic steps to write a JDBC program 3. Import ja!a.s1l and ja!a2.s1l packages 4. 0oad JDBC dri!er 5. 6stablish connection to the database sing Connection inter"ace &. Create a %tatement by passing %/0 1 ery '. 62ec te the %tatement 7. Retrie!e res lts by sing Res lt%et inter"ace 8. Close %tatement and Connection *e will look at these areas one by one, what type o" dri!er yo need to load, how to se Connection inter"ace in the best manner, how to se di""erent %tatement inter"aces, how to process res lts sing Res lt%et and "inally how to optimi9e %/0 1 eries to impro!e JDBC per"ormance.

Choosing the right Driver


:ere I will walk thro gh initially abo t the types o" dri!ers, a!ailability o" dri!ers, se o" dri!ers in di""erent sit ations, and then I will disc ss abo t which dri!er s its yo r application best. Dri!er is the key player in a JDBC application, it acts as a mediator between Ja!a application and database. It implements JDBC +,I inter"aces "or a database, "or e2ample ;racle dri!er "or oracle database, %ybase dri!er "or %ybase database. It maps Ja!a lang age to database speci"ic lang age incl ding %/0. JDBC de"ines "o r types o" dri!ers to work with. Depending on yo r re1 irement yo can choose one among them. :ere is a brie" description o" each type o" dri!er .
Type of Tier driver 1 ! Two Two

Driver mechanism JDBC-ODBC "ative #$% - $artly - Java driver

Description This driver converts JDBC calls to ODBC calls through JDBC-ODBC Bridge driver which in turn converts to database calls. Client re uires ODBC libraries. This driver converts JDBC calls to database specific native calls. Client re uires database specific libraries. This driver passes calls to pro'y server through networ( protocol which in turn converts to database calls and passes through database specific protocol. Client doesn)t re uire any driver. This driver directly calls database. Client doesn)t re uire any driver.

&

Three JDBC - "et -#ll Java driver

Two

"ative protocol - #ll - Java driver

;b!io sly the choice o" choosing a dri!er depends on a!ailability o" dri!er and re1 irement. <enerally all the databases s pport their own dri!ers or "rom third party !endors. I" yo don't ha!e dri!er "or yo r database, JDBC(;DBC dri!er is the only choice beca se all most all the !endors s pport ;DBC. I" yo ha!e tiered re1 irement # two tier or three tier$ "or yo r application, then yo can "ilter down yo r choices, "or e2ample i" yo r application is three tiered, then yo can go "or Type three dri!er between client and pro2y ser!er shown below. I" yo want to connect to database "rom ja!a applet, then yo ha!e to se Type "o r dri!er beca se it is only the dri!er which s pports that "eat re. This "ig re shows the o!erall pict re o" dri!ers "rom tiered perspecti!e.

This "ig re ill strates the dri!ers that can be sed "or two tiered and three tiered applications. =or both two and three tiered applications, yo can "ilter down easily to Type three dri!er b t yo can se Type one, two and "o r dri!ers "or both tiered applications. To be more precise, "or ja!a applications# non( applet$ yo can se Type one, two or "o r dri!er. :ere is e2actly where yo may make a mistake by choosing a dri!er witho t taking per"ormance into consideration. 0et s look at that perspecti!e in the "ollowing section. Type 5 > & dri!ers are "aster than other dri!ers beca se Type 5 gi!es "acility "or optimi9ation techni1 es pro!ided by application ser!er s ch as connection pooling, caching, load balancing etc and Type & dri!er need not translate database calls to ;DBC or nati!e connecti!ity inter"ace. Type 3 dri!ers are slow beca se they ha!e to con!ert JDBC calls to ;DBC thro gh JDBC(;DBC Bridge dri!er initially and then ;DBC Dri!er con!erts them into database speci"ic calls. Type 4 dri!ers gi!e a!erage per"ormance when compared to Type 5 > & dri!ers beca se the database calls ha!e to be con!erted into database speci"ic calls. Type 4 dri!ers gi!e better per"ormance than Type 3 dri!ers. =inally, to impro!e per"ormance 3. ?se Type & dri!er "or applet to database comm nication. 4. ?se Type 4 dri!er "or two tiered applications "or comm nication between ja!a client and the database that gi!es better per"ormance when compared to Type3 dri!er 5. ?se Type 3 dri!er i" yo r database doesn't s pport a dri!er. This is rare sit ation beca se almost all major databases s pport dri!ers or yo will get them "rom third party !endors. &.?se Type 5 dri!er to comm nicate between client and pro2y ser!er # weblogic, websphere etc$ "or three tiered applications that gi!es better per"ormance when compared to Type 3 > 4 dri!ers.

Optimization with Connection


ja!a.s1l package in JDBC pro!ides Connection inter"ace that encaps lates database connection " nctionality. ?sing Connection inter"ace, yo can "ine t ne the "ollowing operations . 3. %et optimal row pre("etch !al e 4. ?se Connection pool 5. Control transaction &. Choose optimal isolation le!el '. Close Connection when "inished 6ach o" these operations e""ects the per"ormance. I will walk thro gh each operation one by one. ! "et optima# row pre$fetch va#ue *e ha!e di""erent approaches to establish a connection with the database, the "irst type o" approach is .
3. Dri!er@anager.getConnection#%tring rl$ 4. Dri!er@anager.getConnection#%tring rl, ,roperties props$ 5. Dri!er@anager.getConnection#%tring rl, %tring ser, %tring password$ &. Dri!er.connect#%tring rl, ,roperties props$

*hen yo se this approach, yo can pass database speci"ic in"ormation to the database by passing properties sing ,roperties object to impro!e per"ormance. =or e2ample, when yo se oracle database

yo can pass de"a lt n mber o" rows that m st be pre("etched "rom the database ser!er and the de"a lt batch !al e that triggers an e2ec tion re1 est. ;racle has de"a lt !al e as 3) "or both properties. By increasing the !al e o" these properties, yo can red ce the n mber o" database calls which in t rn impro!es per"ormance. The "ollowing code snippet ill strates this approach.
ja!a. til.,roperties props A new ja!a. til.,roperties#$B props.p t#C serC,CscottC$B props.p t#CpasswordC,CtigerC$B props.p t#Cde"a ltRow,re"etchC,C5)C$B props.p t#Cde"a ltBatchDal eC,C'C$B Connection con A Dri!er@anger.getConnection#Cjdbc.oracle.thin.EhoststringC, props$B

Fo need to "ig re o t appropriate !al es "or abo!e properties "or better per"ormance depending on application's re1 irement. % ppose, yo want to set these properties "or search "acility, yo can increase de"a ltRow,re"etch so that yo can increase per"ormance signi"icantly. The second type o" approach is to get connection "rom Data%o rce. Fo can get the connection sing ja!a2.s1l.Data%o rce inter"ace. The ad!antage o" getting connection "rom this approach is that the Data%o rce works with JGDI. The implementation o" Data%o rce is done by !endor, "or e2ample yo can "ind this "eat re in weblogic, websphere etc. The !endor simply creates Data%o rce implementation class and binds it to the JGDI tree. The "ollowing code shows how a !endor creates implementation class and binds it to JGDI tree.
Data%o rceImpl dsi A new Data%o rceImpl#$B dsi.set%er!erGame#CoracleHiC$B dsi.setDatabaseGame#CDemoC$B Conte2t ct2 A new InitialConte2t#$B ct2.bind#CjdbcIdemoDBC, dsi$B

This code registers the Data%o rceImpl object to the JGDI tree, then the programmer can get the Data%o rce re"erence "rom JGDI tree witho t knowledge o" the nderlying technology.
Conte2t ct2 A new InitialConte2t#$B Data%o rce ds A #Data%o rce$ct2.look p#CjdbcIdemoDBC$B Connection con A ds.getConnection#$B

By sing this approach we can impro!e per"ormance. Gearly all major !endor application ser!ers like weblogic, webshpere implement the Data%o rce by taking connection "rom connection pool rather than a single connection e!ery time. The application ser!er creates connection pool by de"a lt. I will disc ss the ad!antage o" connection pool to impro!e per"ormance in the ne2t section. %! &se Connection poo# Creating a connection to the database ser!er is e2pensi!e. It is e!en more e2pensi!e i" the ser!er is located on another machine. Connection pool contains a n mber o" open database connections with minim m and ma2im m connections, that means the connection pool has open connections between minim m and ma2im m n mber that yo speci"y. The pool e2pands and shrinks between minim m and ma2im m si9e depending on incremental capacity. Fo need to gi!e minim m, ma2im m and incremental si9es as properties to the pool in order to maintain that " nctionality. Fo get the connection "rom the pool rather directly .=or e2ample, i" yo gi!e properties like min, ma2 and incremental si9es as 5, 3) and 3 then pool is created with si9e 5 initially and i" it reaches it's capacity 5 and i" a client re1 ests a connection conc rrently, it increments its capacity by 3 till it reaches 3) and

later on it p ts all its clients in a 1 e e. There are a "ew choices when sing connection pool. 3. Fo can depend on application ser!er i" it s pports this "eat re, generally all the application ser!ers s pport connection pools. +pplication ser!er creates the connection pool on behal" o" yo when it starts. Fo need to gi!e properties like min, ma2 and incremental si9es to the application ser!er. 4. Fo can se JDBC 4.) inter"aces, Connection,oolData%o rce and ,ooledConnection i" yo r dri!er implements these inter"aces 5. ;r yo can create yo r own connection pool i" yo are not sing any application ser!er or JDBC 4.) compatible dri!er. By sing any o" these options, yo can increase per"ormance signi"icantly. Fo need to take care o" properties like min, ma2 and incremental si9es. The ma2im m n mber o" connections to be gi!en depends on yo r application's re1 irement that means how many conc rrent clients can access yo r database and also it depends p on yo r database's capability to pro!ide ma2im m n mber o" connections. '! Contro# transaction In general, transaction represents one nit o" work or b nch o" code in the program that e2ec tes in it's entirety or none at all. To be precise, it is all or no work. In JDBC, transaction is a set o" one or more %tatements that e2ec te as a single nit. ja!a.s1l.Connection inter"ace pro!ides some methods to control transaction they are
p blic inter"ace Connection J boolean get+ toCommit#$B !oid set+ toCommit#boolean a tocommit$B !oid commit#$B !oid rollback#$B K

JDBC's de"a lt mechanism "or transactions. By de"a lt in JDBC transaction starts and commits a"ter each statement's e2ec tion on a connection. That is the + toCommit mode is tr e. ,rogrammer need not write a commit#$ method e2plicitly a"ter each statement. ;b!io sly this de"a lt mechanism gi!es good "acility "or programmers i" they want to e2ec te a single statement. B t it gi!es poor per"ormance when m ltiple statements on a connection are to be e2ec ted beca se commit is iss ed a"ter each statement by de"a lt, that in t rn red ces per"ormance by iss ing nnecessary commits. The remedy is to "lip it back to + toCommit mode as "alse and iss e commit#$ method a"ter a set o" statements e2ec te, this is called as batch transaction. ?se rollback#$ in catch block to rollback the transaction whene!er an e2ception occ rs in yo r program. The "ollowing code ill strates the batch transaction approach.
tryJ connection.set+ toCommit#"alse$B ,repared%tatement ps A connection.preare%tatement# C?,D+T6 employee %6T +ddressAL *:6R6 nameALC$B ps.set%tring#3,C+ stinC$B ps.set%tring#4,CRRC$B ps.e2ec te?pdate#$B

,repared%tatement ps3 A connection.prepare%tatement# C?,D+T6 acco nt %6T salaryAL *:6R6 nameALC$B ps3.setDo ble#3, '))).))$B ps3.set%tring#4,CRRC$B ps3.e2ec te?pdate#$B connection.commit#$B connection.set+ toCommit#tr e$B K catch#%/062ception e$J connection.rollback#$BK "inallyJ i"#ps MA n ll$J ps.close#$BK i"#ps3 MA n ll$Jps3.close#$BK i"#connection MA n ll$Jconnection.close#$BK K

This batch transaction gi!es good per"ormance by red cing commit calls a"ter each statement's e2ec tion. (! Choose optima# iso#ation #eve# Isolation le!el represent how a database maintains data integrity against the problems like dirty reads, phantom reads and non(repeatable reads which can occ r d e to conc rrent transactions. ja!a.s1l.Connection inter"ace pro!ides methods and constants to a!oid the abo!e mentioned problems by setting di""erent isolation le!els.
p blic inter"ace Connection J p blic static "inal int TR+G%+CTI;GNG;G6 A ) p blic static "inal int TR+G%+CTI;GNR6+DNC;@@ITT6DA 4 p blic static "inal int TR+G%+CTI;GNR6+DN?GC;@@ITT6D A 3 p blic static "inal int TR+G%+CTI;GNR6,6+T+B06NR6+D A & p blic static "inal int TR+G%+CTI;GN%6RI+0IO+B06 A H int getTransactionIsolation#$B !oid setTransactionIsolation#int isolationle!elconstant$B K

Fo can get the e2isting isolation le!el with getTransactionIsolation#$ method and set the isolation le!el with setTransactionIsolation#int isolationle!elconstant$ by passing abo!e constants to this method.

The "ollowing table describes isolation le!el against the problem that it pre!ents .
$erformance impact $hantom reads "0# 4/4/4/"O 1#-T/-T 1#-T/-T 1#-T 3/D%23 -+O6

Transaction +evel Dirty reads T,#"-#CT%O"."O"/ T,#"-#CT%O".,/#D.2" CO33%T/D T,#"-#CT%O".,/#D.CO 33%T/D T,#"-#CT%O".,/$/#T# B+/.,/#D T,#"-#CT%O".-/,%#+%5 #B+/ "0# 4/"O "O "O

$ermitted $henomena "on ,epeatable reads "0# 4/4/"O "O

F6% means that the Isolation le!el does not pre!ent the problem G; means that the Isolation le!el pre!ents the problem By setting isolation le!els, yo are ha!ing an impact on the per"ormance as mentioned in the abo!e table. Database se read and write locks to control abo!e isolation le!els. 0et s ha!e a look at each o" these problems and then look at the impact on the per"ormance. Dirt) read pro*#em : The "ollowing "ig re ill strates Dirty read problem .

%tep 3. Database row has ,R;D?CT A +))3 and ,RIC6 A 3) %tep 4. Connection3 starts Transaction3 #T3$ . %tep 5. Connection4 starts Transaction4 #T4$ . %tep &. T3 pdates ,RIC6 A4) "or ,R;D?CT A +))3

%tep '. Database has now ,RIC6 A 4) "or ,R;D?CT A +))3 %tep 7. T4 reads ,RIC6 A 4) "or ,R;D?CT A +))3 %tep 8. T4 commits transaction %tep H. T3 rollbacks the transaction beca se o" some problem The problem is that T4 gets wrong ,RIC6A4) "or ,R;D?CT A +))3 instead o" 3) beca se o" ncommitted read. ;b!io sly it is !ery dangero s in critical transactions i" yo read inconsistent data. I" yo are s re abo t not accessing data conc rrently then yo can allow this problem by setting TR+G%+CTI;GNR6+DN?GC;@@IT6D or TR+G%+CTI;GNG;G6 that in t rn impro!es per"ormance otherwise yo ha!e to se TR+G%+CTI;GNR6+DNC;@@IT6D to a!oid this problem. &nrepeata*#e read pro*#em : The "ollowing "ig re ill strates ?nrepeatable read problem . %tep 3. Database row has ,R;D?CT A +))3 and ,RIC6 A 3) %tep 4. Connection3 starts Transaction3 #T3$ . %tep 5. Connection4 starts Transaction4 #T4$ . %tep &. T3 reads ,RIC6 A3) "or ,R;D?CT A +))3 %tep '. T4 pdates ,RIC6 A 4) "or ,R;D?CT A +))3 %tep 7. T4 commits transaction %tep 8. Database row has ,R;D?CT A +))3 and ,RIC6 A 4) %tep H. T3 reads ,RIC6 A 4) "or ,R;D?CT A +))3 %tep P. T3 commits transaction :ere the problem is that Transaction3 reads 3) "irst time and reads 4) second time b t it is s pposed to be 3) always whene!er it reads a record in that transaction. Fo can control this problem by setting isolation le!el as TR+G%+CTI;GNR6,6+T+B06NR6+D. Phantom read pro*#em : The "ollowing "ig re ill strates ,hantom read problem .

%tep 3. Database has a row ,R;D?CT A +))3 and C;@,+GFNID A 3) %tep 4. Connection3 starts Transaction3 #T3$ . %tep 5. Connection4 starts Transaction4 #T4$ . %tep &. T3 selects a row with a condition %606CT ,R;D?CT *:6R6 C;@,+GFNID A 3) %tep '. T4 inserts a row with a condition IG%6RT ,R;D?CTA+))4 *:6R6 C;@,+GFNIDA 3) %tep 7. T4 commits transaction %tep 8. Database has 4 rows with that condition %tep H. T3 select again with a condition %606CT ,R;D?CT *:6R6 C;@,+GFNIDA3) and gets 4 rows instead o" 3 row %tep P. T3 commits transaction :ere the problem is that T3 gets 4 rows instead o" 3 row p on selecting the same condition second time. Fo can control this problem by setting isolation le!el as TR+G%+CTI;GN%6RI+0IO+B06 Choosing a right iso#ation #eve# for )our program: Choosing a right isolation le!el "or yo r program depends pon yo r application's re1 irement. In single application itsel" the re1 irement generally changes, s ppose i" yo write a program "or searching a prod ct catalog "rom yo r database then yo can easily choose TR+G%+CTI;GNR6+DN?GC;@@IT6D beca se yo need not worry abo t the problems that are mentioned abo!e, some other program can insert records at the same time, yo don't ha!e to bother m ch abo t that insertion. ;b!io sly this impro!es per"ormance signi"icantly. I" yo write a critical program like bank or stocks analysis program where yo want to control all o" the abo!e mentioned problems, yo can choose TR+G%+CTI;GN%6RI+0IO+B06 "or ma2im m sa"ety. :ere it is the tradeo"" between the sa"ety and per"ormance. ?ltimately we need sa"ety here. I" yo don't ha!e to deal with conc rrent transactions yo r application, then the best choice is TR+G%+CTI;GNG;G6 to impro!e per"ormance. ;ther two isolation le!els need good nderstanding o" yo r re1 irement. I" yo r application needs only committed records, then TR+G%+CTI;GNR6+DNC;@@IT6D isolation is the good choice. I" yo r application needs to read a row e2cl si!ely till yo "inish yo r work, then TR+G%+CTI;GNR6,6+T+B06NR6+D is the best choice. +ote. Be aware o" yo r database ser!er's s pport "or these isolation le!els. Database ser!ers may not s pport all o" these isolation le!els. ;racle ser!er s pports only two isolation le!els, TR+G%+CTI;GNR6+DNC;@@IT6D and TR+G%+CTI;GN%6RI+0IO+B06 isolation le!el, de"a lt isolation le!el is TR+G%+CTI;GNR6+DNC;@@IT6D. ,! C#ose Connection when finished Closing connection e2plicitly allows garbage collector to recollect memory as early as possible. Remember that when yo se the connection pool, closing connection means that it ret rns back to the connection pool rather than closing direct connection to the database.

Optimization with "tatement


%tatement inter"ace represents %/0 1 ery and e2ec tion and they pro!ide n mber o" methods and constants to work with 1 eries. They also pro!ide some methods to "ine t ne per"ormance. ,rogrammer may o!erlook these "ine t ning methods that res lt in poor per"ormance. The "ollowing are the tips to impro!e per"ormance by sing statement inter"aces 3. Choose the right %tatement inter"ace 4. Do batch pdate 5. Do batch retrie!al sing %tatement &. Close %tatement when "inished ! Choose right "tatement interface There are three types o" %tatement inter"aces in JDBC to represent the %/0 1 ery and e2ec te that 1 ery, they are %tatement, ,repared%tatement and Callable%tatement. %tatement is sed "or static %/0 statement with no inp t and o tp t parameters, ,repared%tatement is sed "or dynamic %/0 statement with inp t parameters and Callable%tatement is sed "or dynamic %/0 satement with both inp t and o tp t parameters, b t ,repared%tatement and Callable%tatement can be sed "or static %/0 statements as well. Callable%tatement is mainly meant "or stored proced res. ,repared%tatement gi!es better per"ormance when compared to %tatement beca se it is pre(parsed and pre(compiled by the database once "or the "irst time and then onwards it re ses the parsed and compiled statement. Beca se o" this "eat re, it signi"icantly impro!es per"ormance when a statement e2ec tes repeatedly, It red ces the o!erload inc rred by parsing and compiling. Callable%tatement gi!es better per"ormance when compared to ,repared%tatement and %tatement when there is a re1 irement "or single re1 est to process m ltiple comple2 statements. It parses and stores the stored proced res in the database and does all the work at database itsel" that in t rn impro!es per"ormance. B t we loose ja!a portability and we ha!e to depend p on database speci"ic stored proced res. %! Do *atch update Fo can send m ltiple 1 eries to the database at a time sing batch pdate "eat re o" statement objects this red ces the n mber o" JDBC calls and impro!es per"ormance. :ere is an e2ample o" how yo can do batch pdate,
statement.addBatch# Cs1l 1 ery3C$B statement.addBatch#C s1l 1 ery4C$B statement.addBatch#C s1l 1 ery5C$B statement.e2ec teBatch#$B

+ll three types o" statements ha!e these methods to do batch pdate. '! Do *atch retrieva# using "tatement Fo can get the de"a lt n mber o" rows that is pro!ided by the dri!er. Fo can impro!e per"ormance by increasing n mber o" rows to be "etched at a time "rom database sing set=etch%i9e#$ method o" the statement object. Initially "ind the de"a lt si9e by sing
%tatement.get=etch%i9e#$B and

then set the si9e as per yo r re1 irement

%tatement.set=etch%i9e#5)$B

:ere it retrie!es 5) rows at a time "or all res lt sets o" this statement. (! C#ose "tatement when finished Close statement object as soon as yo "inish working with that, it e2plicitly gi!es a chance to garbage collector to recollect memory as early as possible which in t rn e""ects per"ormance.
%tatement.close#$B

Optimization with -esu#t"et


Res lt%et inter"ace represents data that contains the res lts o" e2ec ting an %/0 / ery and it pro!ides a n mber o" methods and constants to work with that data. It also pro!ides methods to "ine t ne retrie!al o" data to impro!e per"ormance. The "ollowing are the "ine t ning tips to impro!e per"ormance by sing Res lt%et inter"ace. 3. Do batch retrie!al sing Res lt%et 4. %et p proper direction "or processing the rows 5. ?se proper get methods &. Close Res lt%et when "inished ! Do *atch retrieva# using -esu#t"et Res lt%et inter"ace also pro!ides batch retrie!al "acility like %tatement as mentioned abo!e. It o!errides the %tatement beha!io r. Initially "ind the de"a lt si9e by sing
Res lt%et.get=etch%i9e#$B

and then set the si9e as per re1 irement

Res lt%et.set=etch%i9e#')$B

This "eat re signi"icantly impro!es per"ormance when yo are dealing with retrie!al o" large n mber o" rows like search " nctionality. %! "etup proper direction of processing rows Res lt%et has the capability o" setting the direction in which yo want to process the res lts, it has three constants "or this p rpose, they are
=6TC:N=;R*+RD, =6TC:NR6D6R%6, =6TC:N?GQG;*G

Initially "ind the direction by sing


Res lt%et.get=etchDirection#$B and

then set the direction accordingly

Res lt%et.set=etchDirection#=6TC:NR6D6R%6$B

'! &se proper get.../0 methods Res lt%et inter"ace pro!ides lot o" get222#$ methods to get and con!ert database data types to ja!a data types and is "le2ibile in con!erting non "easible data types. =or e2ample, get%tring#%tring col mnGame$ ret rns ja!a %tring object. col mnGame is recommended to be a D+RC:+R ;R C:+R type o" database b t it can also be a G?@6RIC, D+T6 etc. I" yo gi!e non recommended parameters, it needs to cast it to proper ja!a data type that is e2pensi!e. =or e2ample consider that yo select a prod ct's id "rom h ge database which ret rns millions o"

records "rom search " nctionality, it needs to con!ert all these records that is !ery e2pensi!e. %o always se proper get222#$ methods according to JDBC recommendations. (! C#ose -esu#t"et when finished Close Res lt%et object as soon as yo "inish working with Res lt%et object e!en tho gh %tatement object closes the Res lt%et object implicitly when it closes, closing Res lt%et e2plicitly gi!es chance to garbage collector to recollect memory as early as possible beca se Res lt%et object may occ py lot o" memory depending on 1 ery.
Res lt%et.close#$B

Optimization with "12 1uer)


This is one o" the area where programmers generally make a mistake I" yo gi!e a 1 ery like
%tatement stmt A connection.create%tatement#$B Res lt%et rs A stmt.e2ec te/ ery#Cselect R "rom employee where nameARRC$B

The ret rned res lt set contains all the col mns data. yo may not need all the col mn data and want only salary "or RR. The better 1 ery is Cselect salary "rom employee where nameARRC It ret rns the re1 ired data and red ces nnecessary data retrie!al.

Cache the read$on#) and read$most#) data


6!ery database schema generally has read(only and read(mostly tables. These tables are called as look p tables. Read(only tables contain static data that ne!er changes in its li"e time. Read(mostly tables contain semi dynamic data that changes o"ten. There will not be any sort o" writing operations in these tables. I" an application reads data "rom these tables "or e!ery client re1 est, then it is red ndant, nnecessary and e2pensi!e. The sol tion "or this problem is to cache the read(only table data by reading the data "rom that table once and caching the read(mostly table data by reading and re"reshing with time limit. This sol tion impro!es per"ormance signi"icantly. %ee the "ollowing link "or so rce code o" s ch caching mechanism.
http.IIwww.ja!aworld.comIja!aworldIjw()8(4))3Ijw()84)(cache.html

Fo can tweak this code as per application re1 irement. =or read(only data, yo need not re"resh data in its li"e time. =or read(mostly data, yo need to re"resh the data with time limit. It is better to set this re"reshing time limit in properties "ile so that it can be changed at any time.

3etch sma## amount of data iterative#) instead of fetching who#e data at once
+pplications generally re1 ire to retrie!e h ge data "rom the database sing JDBC in operations like searching data. I" the client re1 est "or a search, the application might ret rn the whole res lt set at once. This process takes lot o" time and has an impact on per"ormance. The sol tion "or the problem is

3. Cache the search data at the ser!er(side and ret rn the data iterati!ely to the client. =or e2ample, the search ret rns 3))) records, ret rn data to the client in 3) iterations where each iteration has 3)) records. 4. ?se %tored proced res to ret rn data iterati!ely. This does not se ser!er(side caching rather ser!er( side application ses %tored proced res to ret rn small amo nt o" data iterati!ely. ; t o" these sol tions the second sol tion gi!es better per"ormance beca se it need not keep the data in the cache #in(memory$. The "irst proced re is se" l when the total amo nt o" data to be ret rned is not h ge.

4e) Points
3. ?se Type two dri!er "or two tiered applications to comm nicate "rom ja!a client to database that gi!es better per"ormance than Type3 dri!er. 4. ?se Type "o r dri!er "or applet to database comm nication that is two tiered applications and three tiered applications when compared to other dri!ers. 5. ?se Type one dri!er i" yo don't ha!e a dri!er "or yo r database. This is a rare sit ation beca se all major databases s pport dri!ers or yo will get a dri!er "rom third party !endors. &. ?se Type three dri!er to comm nicate between client and pro2y ser!er # weblogic, websphere etc$ "or three tiered applications that gi!es better per"ormance when compared to Type 3 >4 dri!ers. '. ,ass database speci"ic properties like de"a lt,re"etch i" yo r database s pports any o" them. 7. <et database connection "rom connection pool rather than getting it directly 8. ?se batch transactions. H. Choose right isolation le!el as per yo r re1 irement. TR+G%+CTI;GNR6+DN?GC;@@IT6D gi!es best per"ormance "or conc rrent transaction based applications. TR+G%+CTI;GNG;G6 gi!es best per"ormance "or non(conc rrent transaction based applications. P. Fo r database ser!er may not s pport all isolation le!els, be aware o" yo r database ser!er "eat res. 3).?se ,repared%tatement when yo e2ec te the same statement more than once. 33.?se Callable%tatement when yo want res lt "rom m ltiple and comple2 statements "or a single re1 est. 34.?se batch pdate "acility a!ailable in %tatements. 35.?se batch retrie!al "acility a!ailable in %tatements or Res lt%et. 3&.%et p proper direction "or processing rows. 3'.?se proper getSSS#$ methods. 37.Close Res lt%et, %tatement and Connection whene!er yo "inish yo r work with them. 38.*rite precise %/0 1 eries. 3H.Cache read(only and read(mostly tables data.

3P.=etch small amo nt o" data iterati!ely rather than whole data at once when retrie!ing large amo nt o" data like searching database etc. Re"erences. (- www.onja!a.com (- www.preciseja!a.com (- www.ja!aper"ormancet ning.com

You might also like