You are on page 1of 10

J2EE - Performance 1 . What are common optimizing practices for a class?

* Use primitive data types instead of objects as instance variables * Keep constructors simple and inheritance hierarchies shallow * Avoid initializing instance variable more than once * Eliminate unnecessary type casts * Enumerators are faster than Iterators due to the specific implementation * Ints are the fastest datatype * Use static variables for fields that only need to be assigned once * Final classes can be faster * Use interfaces so that the actual underlying data structure can be actually changed without impacting the client program * !ull out references when they are no longer needed so that gc can collect them when it is running" * Avoid character processing using methods li#e charAt$% set&harAt$% methods * Use local variables in preference to class variables * &ompound operators such as n '( )* are faster than n ( n ' )* because fewer bytecodes are generated" * +hifting by powers of two is faster than multiplying" * ,ultiplication is faster than e-ponentiation" * int increments are faster than byte or short increments" * Floating point increments are much slower than any integral increment" * It can help to copy slower.access vars to fast local vars if you are going to operate on them repeatedly as in a loop" * For some applications that access the date a lot it can help to set the local timezone to be /,0 so that no conversion has to ta#e place" * ,inimize creation of short.lived objects" * Avoid e-cessive writing to the 1ava console * ,inimize the number of 1!I calls * Avoid unnecessary instanceof operation * Avoid using long divides" * 2ersistency adds overheads that ma#e persistent objects slower" * Use pipelining and parallelism" 3esigning applications to support lots of parallel processes wor#ing on easily distinguished subsets of the wor# ma#es the application faster" If there are multiple steps to processing try to design your application so that subse4uent steps can start wor#ing on the portion of data that any prior process has finished instead of having to wait until the prior process is complete" * Use bitshift instead of multiplying or dividing by powers of 5" * +cope of variables can impact performance" * Avoid repeatedly e-ecuting a parse 6or other constant e-pression7 in a loop when the e-ecution can be achieved once outside the loop" * Use e-ception only where you need them 2 . How do you optimize methods in a class? * Avoid creating temporary objects within fre4uently called methods * 3efine methods that accept reusable objects to be filled in with data rather than methods that return objects holding that data" * Use methods that alter objects without ma#ing copies * Eliminate repeatedly called methods where alternatives are possible 6For e-ample if you are processing a vector in a loop get the size of the vector in the beginning in a length local variable rather than calling size$% method on the vector in the condition part of the for loop7 * Use private and static methods and final classes to encourage inlining by the compiler * Inline methods manually where it is appropriate 8

* Keep methods short and simple to ma#e them automatic inlining candidates * Access to private member by the inner classes to the enclosing class goes by a method call even if it is not intended to" * Keep synchronized methods out of loops if you possibly can" . How do you optimize loops and conditional statements? * 9educe the number of temporary objects being used especially in loops" * Use short.circuit :oolean operators instead of normal :oolean operators * Eliminate unnecessary repeated method calls from loops * ,ove loop invariants outside the loop" * 2erform the loop bac#wards $this actually performs slightly faster than forward loops do%" 6Actually it is converting the test to compare against ; that ma#es the difference7" * It can help to copy slower.access vars to fast local vars if you are going to operate on them repeatedly as in a loop" * Use e-ception terminated infinite loops for long loops" * <hatever can be calculated outside of a loop should be calculated outside of the loop" * For multidimensional arrays store a reference for the currently accessed row in a variable" * &ache the size of the collection in a local variable to use in a loop instead of repeatedly calling collection"size$%" ! . How do you optimize "trings? * Use +tring:uffer instead of +tring concat ='= operator * Formatting numbers using java"te-t"3ecimalFormat is always slower than 3ouble"to+tring$double% method because internally java"te-t"3ecimalFormat$% calls 3ouble"to+tring$double% then parses and converts the results" * &onvert +tring to char67 arrays to process characters rather than accessing one at a time using +tring"charAt$% method * &reating 3ouble from string is slow * Intern$% +trings to enable $((% comparisions * Use char arrays for all character processing in loops rather than using +tring or +tring:uffer classes * +et the initial string buffer size to ma-imum if it #nown" * +tring0o#enizer is very inefficient and can be optimized by storing the string and delimiter in a character array instead of in +tring * 3>!=0 create static strings via new$%" * <here the compiler cannot resolve concatenated strings at compile time the code should be converted to +tring:uffer appends and the +tring:uffer should be appropriately sized rather than using the default size" * 0he compiler concatenates strings where they are fully resolvable so don t move these concatenations to runtime with +tring:uffer" # . How do you optimize arrays$ %ectors and collections? * &reate copies of simple array by initializing them through loops or by using +ystem"arraycopy$% create copies of comple- arrays by cloning them * Iterator"has!e-t$% and Enumerator"has,oreElements$% need not be repeatedly called when the size of the collection is #nown" Use collection"size$% and a loop counter instead" * Array?ist is faster than @ector * /o for a non.synchronized version of collection unless used in a threaded application * ?in#ed?ist is faster than Array?ist for inserting elements to the front of the array but slower at inde-ed loo#up * Accessing arrays is much faster than accessing vectors +tring and +tring:uffer * @ector is convenient to use but inefficient" Ensure that elementAt$% is not used inside a loop" * 9e.use Aashtables by using Aashtable"clear$%" * 9emoving elements from a @ector will necessitate copying within the @ector if the element is removed from anywhere other than the end of the collection" 5

* 2resizing collections to the e-pected size is more efficient than using the default size and letting the collection grow" * For multidimensional arrays store a reference for the currently accessed row in a variable" * <hen adding multiple items to a collection add them all in one call if possible" & . How do you optimize threads? * Avoid synchronization where possible * &ode a multi.thread for multi.processor machine" * +ynchronizing on method rather than code bloc#s is slightly faster * 2olling is only acceptable when waiting for outside events and should be performed in a BsideB thread" Use waitCnotify instead" * 2rioritize threads" Use notify instead of notifyAll" Use synchronization sparingly" * Keep synchronized methods out of loops if you possibly can" * ,a-imize thread lifetimes and minimize thread creationCdestruction cycles" * Use 0hread pools where these improve performance" * Use 0hread"sleep$% instead of a for loop for measured delays" * Use a separate timer thread to timeout soc#et operations * Use more server threads if multiple connections have high latency" ' . How do you optimize ()? * Use :uffered I> classes * File information such as file length re4uires a system call and can be slow" 3on=t use it often" +imilarly +ystem"current0ime,illis$% uses a native call to get current time" ,a#e sure your production code does not have this statement" * ,any java"io"File methods are system calls which can be slow * Use :ufferedI> streams to access U9?&onnection sInputC>utput streams" * Use the transient #eyword to define fields to avoid having those fields serialized" E-amine serialized objects to determine which fields do not need to be serialized for the application to wor#" * Increase server listen 4ueues for high load or high latency servers" * . How do you optimize e+ceptions? * :e specific while handling the e-ception in your catch bloc#" * :e specific while throwing e-ception in your throws clause" * 3o not use E-ception Aandling to control programming flow" * @ery little overhead is imposed by using e-ception handling mechanism unless an e-ception occurs or thrown a new e-ception object e-plicitly" * Always use the finally bloc# to release the resources to prevent resource lea#s" * Aandle e-ceptions locally wherever possible" * 3o not use E-ception handling in loops" , . How will you optimize performance in J-./? * Use batch transactions" * &hoose right isolation level as per your re4uirement" 09A!+A&0I>!D9EA3DU!&>,,I0E3 gives best performance for concurrent transaction based applications" 09A!+A&0I>!D!>!E gives best performance for non. concurrent transaction based applications" * Use 2repared+tatement when you e-ecute the same statement more than once" * Use &allable+tatement when you want result from multiple and comple- statements for a single re4uest" E

* Use batch update facility available in +tatements" * Use batch retrieval facility available in +tatements or 9esult+et" * +et up proper direction for processing rows" * Use proper getFFF$% methods" * &lose 9esult+et +tatement and &onnection whenever you finish your wor# with them" * <rite precise +G? 4ueries" * &ache read.only and read.mostly tables data" * Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data li#e searching database etc" 10 . How do you optimize ser%lets? * Use init$% method to cache static data * Use +tring:uffer rather than using ' operator when you concatenate multiple strings * Use print$% method rather than println$% method * Use +ervlet>utput+tream rather than 2rint<riter to send binary data * Initialize the 2rint<riter with proper size * Flush the data partly * ,inimize code in the synchronized bloc# * +et the content length * 9elease resources in destroy$% method" * Implement get?ast,odified$% method to use browser cache and server cache * Use application server caching facility * Use ,i-ed session mechanisms such as Attp+ession with hidden fields * 9emove Attp+ession objects e-plicitly in your program whenever you finish the tas# * 9educe session time out value as much as possible * Use =transient= variables to reduce serialization overhead if your Attp+ession trac#ing mechanism uses serialization process" * 3isable servlet auto reloading feature" * Use thread pool for your servlet engine and define the size as per application re4uirement" 11 . How do you optimize a J"P page? * Use jspInit$% method to cache static data * Use +tring:uffer rather than using ' operator when you concatenate multiple strings * Use print$% method rather than println$% method * Use +ervlet>utput+tream instead of 1+2<riter to send binary data * Initialize the =out= object $implicit object% with proper size in the page directive" * Flush the data partly * ,inimize code in the synchronized bloc# * +et the content length * 9elease resources in jsp3estroy$% method" * /ive =false= value to the session in the page directive to avoid session object creation" * Use 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 =use:ean= action" * 3o not use custom tags if you do not have reusability" * Use application server caching facility * Use ,i-ed session mechanisms such as =session= with hidden fields * Use =session= and =application= as cache" * Use caching tags provided by different organizations li#e open+ymphony"com * 9emove =session= objects e-plicitly in your program whenever you finish the tas# )

* 9educe session time out value as much as possible * Use =transient= variables to reduce serialization overhead if your session trac#ing mechanism uses serialization process" * 3isable 1+2 auto reloading feature" * Use thread pool for your 1+2 engine and define the size of thread pool as per application re4uirement"

12 . What are common optimizing practices for EJ.? * Use ?ocal interfaces that are available in E1:5"; if you deploy both E1: &lient and E1: in the same E1: +erver" * Use @endor specific pass.by.reference implementation to ma#e E1:8"8 remote E1:s as ?ocal E1:s if you deploy both E1: &lient and E1: in the same E1: +erver" * <rap entity beans with session beans to reduce networ# calls and to promote declarative transactions" >ptionally ma#e entity beans as local beans where appropriate" * ,a#e coarse grained session and entity beans to reduce networ# calls" * &ontrol serialization by modifying unnecessary data variables with =transient= #ey word to avoid unnecessary data transfer over networ#" * &ache E1:Aome references to avoid 1!3I loo#up overhead" * Avoid transaction overhead for non.transactional methods of session beans by declaring =!ot+upported= or =!ever= transaction attributes that avoid further propagation of transactions" * +et proper transaction age$time.out% to avoid large transaction" * Use clustering for scalability" * 0une thread count for E1: +erver to increase E1: +erver capacity" * &hoose servlet=s Attp+ession object rather than +tateful session bean to maintain client state if you don=t re4uire component architecture and services of +tateful session bean" * &hoose best E1: +erver by testing with E&perf tool #it" * &hoose normal java object over E1: if you don=t want built.in services such as 9,ICII>2 transactions security persistence resource pooling thread safe client state etc""

1 . How do you optimize stateless session 1eans? * 0une the +tateless session beans pool size to avoid overhead of creation and destruction of beans" * Use set+ession&onte-t$% or ejb&reate$% method to cache bean specific resources" * 9elease ac4uired resources in ejb9emove$% method 1! . How do you optimize stateful session 1eans? * 0une +tateful session beans cache size to avoid overhead of activation and passivation process" * +et optimal +tateful session bean age$time.out% to avoid resource congestion" * Use =transient= #ey word for unnecessary variables of +tateful session bean to avoid serialization overhead" * 9emove +tateful session beans e-plicitly from client using remove$% method" 1# . How do you optimize entity 1eans? * 0une the entity beans pool size to avoid overhead of creation and destruction of beans" * 0une the entity beans cache size to avoid overhead of activation passivation and database calls" * Use setEntity&onte-t$% method to cache bean specific resources" * 9elease ac4uired resources in un+etEntity&onte-t$% method * Use ?azy loading to avoid unnecessary pre.loading of child data" H

* &hoose optimal transaction isolation level to avoid bloc#ing of other transactional clients" * Use proper loc#ing strategy" * ,a#e read.only entity beans for read only operations" * Use dirty flag to avoid unchanged buffer data updation" * &ommit the data after the transaction completes to reduce database calls in between transaction" * 3o bul# updates to reduce database calls" * Use &,2 rather than :,2 to utilize built.in performance optimization facilities of &,2" * Use ejbAome$% methods for global operations" * 0une connection pool size to reduce overhead of creation and destruction of database connections" * Use 13:& tuning techni4ues in :,2" * Use direct 13:& rather than using entity beans when dealing with huge data such as searching a large database" * Use business logic that is specific to entity bean data" 1& . How do you optimize message dri%en 1eans? * 0une the ,essage driven beans pool size to promote concurrent processing of messages" * Use set,esssage3riven&onte-t$% or ejb&reate$% method to cache bean specific resources" * 9elease ac4uired resources in ejb9emove$% method" * Use 1,+ tuning techni4ues in ,essage driven beans" 1' . How do you optimize Ja%a 2essage "er%ice 3J2"4 * +tart producer connection after you start consumer" * Use concurrent processing of messages" * &lose the &onnection when finished" * &hoose either 3U2+D>KDA&K!><?E3/E or AU0>DA&K!><?E3/E rather than &?IE!0DA&K!><?E3/E" * &ontrol transactions by using separate transactional session for transactional messages and non.transactional session for non.transactional messages" * &lose session object when finished" * ,a#e 3estination with less capacity and send messages accordingly" * +et high 9edelivery delay time to reduce networ# traffic" * +et less 9edelivery limit for reducing number of message hits" * &hoose non.durable messages wherever appropriate to avoid persistence overhead" * +et optimal message age $0ime0o?ive value%" * 9eceive messages asynchronously" * &lose 2roducerC&onsumer when finished" * &hoose message type carefully to avoid unnecessary memory overhead" * Use =transient= #ey word for variables of >bject,essage which need not be transferred"

The Purpose of the Marker Interface >ne of the BcleanB features of the 1ava programming language is that it mandates a separation between interfaces $pure behavior% and classes $state and behavior%" Interfaces are used in 1ava to specify the behavior of derived classes" >ften you will come across interfaces in 1ava that have no behavior" In other words they are just empty interface definitions" 0hese are #nown as mar#er interfaces" +ome e-amples of mar#er interfaces in the 1ava A2I includeI
- java,lang.Cloneable - java,io.Serializable - java.util.EventListener

,ar#er interfaces are also called BtagB interfaces since they tag all the derived classes into a category based on their purpose" For e-ample all classes that implement the &loneable interface can be cloned $i"e" the clone$% method can be called on them%" 0he 1ava compiler chec#s to ma#e sure that if the clone$% method is called on a class and the class implements the &loneable interface" For e-ample consider the following call to the clone$% method on an object oI
SomeObject o = new SomeObject(); SomeObject re = (SomeObject)(o.clone());

If the class +ome>bject does not implement the interface &loneable $and &loneable is not implemented by any of the superclasses that +ome>bject inherits from% the compiler will mar# this line as an error" 0his is because the clone$% method may only be called by objects of type B&loneable"B Aence even though &loneable is an empty interface it serves an important purpose" Hoe to pre%ent creating more than 2 instances of class? 5ns. public class ,a-5>bjectFor&lass K private static int counter ( 8* CC2rivate constructor to ensure that no.one other than this class itself can create the object" private ,a-5>bjectFor&lass$% K +ystem"out"println$B inside constructor counter ..LB'counter%* M public static ,a-5>bjectFor&lass create>bject$% K ,a-5>bjectFor&lass obj* if$counterL5% K +ystem"out"println$BNou cannot create more than 5 objectB%* obj ( null* M else K obj ( new ,a-5>bjectFor&lass$%* counter''* M return obj* M C** * Oparam args *C public static void main$+tring67 args% K +ystem"out"println$BAello <orldPB%* ,a-5>bjectFor&lass obj8 ( ,a-5>bjectFor&lass"create>bject$%* ,a-5>bjectFor&lass obj5 ( ,a-5>bjectFor&lass"create>bject$%* ,a-5>bjectFor&lass objE ( ,a-5>bjectFor&lass"create>bject$%* ,a-5>bjectFor&lass obj) ( ,a-5>bjectFor&lass"create>bject$%* if$obj8 P( null% +ystem"out"println$Bobj8"hash&ode$% ...LB'obj8"hash&ode$%%* if$obj5 P( null% +ystem"out"println$Bobj5"hash&ode$% ...LB'obj5"hash&ode$%%*

if$objE P( null% +ystem"out"println$BobjE"hash&ode$% ...LB'objE"hash&ode$%%* if$obj) P( null% +ystem"out"println$Bobj)"hash&ode$% ...LB'obj)"hash&ode$%%* M M Ja%a "ingleton -esign Pattern 1ava has several design patterns "ingleton Pattern being the most commonly used" Ja%a "ingleton pattern belongs to the family of design patterns that govern the instantiation process" 0his design pattern proposes that at any time there can only be one instance of a singleton $object% created by the 1@," 0he classRs default constructor is made private which prevents the direct instantiation of the object by others $>ther &lasses%" A static modifier is applied to the instance method that returns the object as it then ma#es this method a class level method that can be accessed without creating an object" >ne such scenario where it might prove useful is when we develop the help ,odule in a project" 1ava Aelp is an e-tensible platform.independent help system that enables authors and developers to incorporate online help into applications" +ingletons can be used to create a &onnection 2ool" If programmers create a new connection object in every class that re4uires it then its clear waste of resources" In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application" (mplementing "ingleton Pattern 0o implement this design pattern we need to consider the following ) stepsI +tep 8I 2rovide a default 2rivate constructor
!ublic class SingletonObject"emo # $$ %ote t&at t&e constructor is !rivate !rivate SingletonObject"emo() # $$ O!tional Co'e ( (

+tep 5I &reate a ,ethod for getting the reference to the +ingleton >bject
!ublic class SingletonObject"emo # !rivate static SingletonObject singletonObject; $$ %ote t&at t&e constructor is !rivate !rivate SingletonObject"emo() # $$ O!tional Co'e ( !ublic static SingletonObject"emo getSingletonObject() # i (singletonObject == null) # singletonObject = new SingletonObject"emo(); ( return singletonObject; ( (

<e write a public static getter or access method to get the instance of the +ingleton >bject at runtime" First time the object is created inside this method as it is null" +ubse4uent calls to this method returns the same object created as the object is globally declared $private% and the hence the same referenced object is returned" S

+tep EI ,a#e the Access method +ynchronized to prevent 0hread 2roblems" public static synchronized +ingleton>bject3emo get+ingleton>bject$% It could happen that the access method may be called twice from 5 different classes at the same time and hence more than one object being created" 0his could violate the design patter principle" In order to prevent the simultaneous invocation of the getter method by 5 threads or classes simultaneously we add the synchronized #eyword to the method declaration +tep )I >verride the >bject clone method to prevent cloning <e can still be able to create a copy of the >bject by cloning it using the >bjectRs clone method" 0his can be done as shown below +ingleton>bject3emo cloned>bject ( $+ingleton>bject3emo% obj"clone$%* 0his again violates the +ingleton 3esign 2atternRs objective" +o to deal with this we need to override the >bjectRs clone method which throws a &lone!ot+upportedE-ception e-ception" public >bject clone$% throws &lone!ot+upportedE-ception K throw new &lone!ot+upportedE-ception$%* M 0he below program shows the final Implementation of +ingleton 3esign 2attern in java by using all the ) steps mentioned above"
class SingletonClass # !rivate static SingletonClass singletonObject; $)) * !rivate Constructor !revents an+ ot&er class rom instantiating. )$ !rivate SingletonClass() # $$ O!tional Co'e ( !ublic static s+nc&ronize' SingletonClass getSingletonObject() # i (singletonObject == null) # singletonObject = new SingletonClass(); ( return singletonObject; ( !ublic Object clone() t&rows Clone%otSu!!orte'E,ce!tion # t&row new Clone%otSu!!orte'E,ce!tion(); ( ( !ublic class SingletonObject"emo # !ublic static voi' main(String args-.) # $$ SingletonClass obj = new SingletonClass(); $$Com!ilation error not allowe' SingletonClass obj = SingletonClass.getSingletonObject(); $$ /our 0usiness Logic S+stem.out.!rintln(1Singleton object obtaine'1); (

Another approach <e donRt need to do a lazy initialization of the instance object or to chec# for null in the get method" <e can also ma#e the singleton class final to avoid sub classing that may cause other problems"
!ublic class SingletonClass # !rivate static SingletonClass our2nstance = new SingletonClass();

!ublic static SingletonClass get2nstance() # return singletonObj; ( !rivate SingletonClass() # ( (

In +ummary the job of the +ingleton class is to enforce the e-istence of a ma-imum of one object of the same type at any given time" 3epending on your implementation your class and all of its data might be garbage collected" Aence we must ensure that at any point there must be a live reference to the class when the application is running" what are the other ways to create an object otherthan creating as new objectU 0here are four different ways $I really donRt #now is there a fifth way to do this% to create objects in javaI 1. 6sing new 7eyword 0his is the most common way to create an object in java" I read somewhere that almost TTV of objects are created in this way"
3+Object object = new 3+Object();

2. 6sing /lass.for8ame34 If we #now the name of the class W if it has a public default constructor we can create an object in this way"
3+Object object = (3+Object) Class. or%ame(1subin.rn'.3+Object1).new2nstance();

. 6sing clone34 0he clone() can be used to create a copy of an e-isting object"
3+Object anot&erObject = new 3+Object(); 3+Object object = anot&erObject.clone();

!. 6sing o19ect deserialization >bject deserialization is nothing but creating an object from its serialized form"
Object2n!utStream inStream = new Object2n!utStream(an2n!utStream ); 3+Object object = (3+Object) inStream.rea'Object();

!ow you #now how to create an object" :ut its advised to create objects only when it is necessary to do so" this"get&lass$%"get&lass?oader$%"load&lass$Xcom"amar"myobjectX%"newInstance$%*

8;

You might also like