performance issue

14

Click here to load reader

Upload: debojyotis

Post on 12-May-2017

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Performance Issue

J2EE - Performance1 . 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 * Null out references when they are no longer needed so that gc can collect them when it is running. * Avoid character processing using methods like charAt(), setCharAt() methods * Use local variables in preference to class variables * Compound operators such as n += 4; are faster than n = n + 4; because fewer bytecodes are generated. * Shifting by powers of two is faster than multiplying. * Multiplication is faster than exponentiation. * 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 GMT, so that no conversion has to take place. * Minimize creation of short-lived objects. * Avoid excessive writing to the Java console * Minimize the number of JNI calls * Avoid unnecessary instanceof operation * Avoid using long divides. * Persistency adds overheads that make persistent objects slower. * Use pipelining and parallelism. Designing applications to support lots of parallel processes working on easily distinguished subsets of the work makes the application faster. If there are multiple steps to processing, try to design your application so that subsequent steps can start working 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 2. * Scope of variables can impact performance. * Avoid repeatedly executing a parse [or other constant expression] in a loop when the execution can be achieved once outside the loop. * Use exception only where you need them

2 . How do you optimize methods in a class?

* Avoid creating temporary objects within frequently called methods * Define 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 making copies * Eliminate repeatedly called methods where alternatives are possible [For example, 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 loop] * Use private and static methods and final classes to encourage inlining by the compiler * Inline methods manually where it is appropriate

1

Page 2: Performance Issue

* Keep methods short and simple to make 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.

3 . How do you optimize loops and conditional statements?

* Reduce the number of temporary objects being used,especially in loops. * Use short-circuit Boolean operators instead of normal Boolean operators * Eliminate unnecessary repeated method calls from loops * Move loop invariants outside the loop. * Perform the loop backwards (this actually performs slightly faster than forward loops do). [Actually it is converting the test to compare against 0 that makes the difference]. * 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 exception terminated infinite loops for long loops. * Whatever 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. * Cache the size of the collection in a local variable to use in a loop instead of repeatedly calling collection.size().

4 . How do you optimize Strings?

* Use StringBuffer instead of String concat '+' operator * Formatting numbers using java.text.DecimalFormat is always slower than Double.toString(double) method, because internally java.text.DecimalFormat() calls Double.toString(double) then parses and converts the results. * Convert String to char[] arrays to process characters rather than accessing one at a time using String.charAt() method * Creating Double from string is slow * Intern() Strings to enable (==) comparisions * Use char arrays for all character processing in loops, rather than using String or StringBuffer classes * Set the initial string buffer size to maximum if it known. * StringTokenizer is very inefficient, and can be optimized by storing the string and delimiter in a character array instead of in String * DON'T create static strings via new(). * Where the compiler cannot resolve concatenated strings at compile time, the code should be converted to StringBuffer appends, and the StringBuffer should be appropriately sized rather than using the default size. * The compiler concatenates strings where they are fully resolvable, so don t move these concatenations to runtime with StringBuffer.

5 . How do you optimize arrays, vectors and collections?

* Create copies of simple array by initializing them through loops or by using System.arraycopy(), create copies of complex arrays by cloning them * Iterator.hasNext() and Enumerator.hasMoreElements() need not be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead. * ArrayList is faster than Vector * Go for a non-synchronized version of collection unless used in a threaded application * LinkedList is faster than ArrayList for inserting elements to the front of the array, but slower at indexed lookup * Accessing arrays is much faster than accessing vectors, String, and StringBuffer * Vector is convenient to use, but inefficient. Ensure that elementAt() is not used inside a loop. * Re-use Hashtables by using Hashtable.clear(). * Removing elements from a Vector will necessitate copying within the Vector if the element is removed from anywhere other than the end of the collection.

2

Page 3: Performance Issue

* Presizing collections to the expected 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. * When adding multiple items to a collection, add them all in one call if possible.

6 . How do you optimize threads?

* Avoid synchronization where possible * Code a multi-thread for multi-processor machine. * Synchronizing on method rather than code blocks is slightly faster * Polling is only acceptable when waiting for outside events and should be performed in a "side" thread. Use wait/notify instead. * Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly. * Keep synchronized methods out of loops if you possibly can. * Maximize thread lifetimes and minimize thread creation/destruction cycles. * Use Thread pools where these improve performance. * Use Thread.sleep() instead of a for loop for measured delays. * Use a separate timer thread to timeout socket operations * Use more server threads if multiple connections have high latency.

7 . How do you optimize IO?

* Use Buffered IO classes * File information such as file length requires a system call and can be slow. Don't use it often. Similarly, System.currentTimeMillis() uses a native call to get current time. Make sure your production code does not have this statement. * Many java.io.File methods are system calls which can be slow * Use BufferedIO streams to access URLConnection sInput/Output streams. * Use the transient keyword to define fields to avoid having those fields serialized. Examine serialized objects to determine which fields do not need to be serialized for the application to work. * Increase server listen queues for high load or high latency servers.

8 . How do you optimize exceptions?

* Be specific while handling the exception in your catch block. * Be specific while throwing exception in your throws clause. * Do not use Exception Handling to control programming flow. * Very little overhead is imposed by using exception handling mechanism unless an exception occurs or thrown a new exception object explicitly. * Always use the finally block to release the resources to prevent resource leaks. * Handle exceptions locally wherever possible. * Do not use Exception handling in loops.

9 . How will you optimize performance in JDBC?

* Use batch transactions. * Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications. * Use PreparedStatement when you execute the same statement more than once. * Use CallableStatement when you want result from multiple and complex statements for a single request.

3

Page 4: Performance Issue

* Use batch update facility available in Statements. * Use batch retrieval facility available in Statements or ResultSet. * Set up proper direction for processing rows. * Use proper getXXX() methods. * Close ResultSet, Statement and Connection whenever you finish your work with them. * Write precise SQL queries. * Cache 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 like searching database etc.

10 . How do you optimize servlets?

* Use init() method to cache static data * Use StringBuffer rather than using + operator when you concatenate multiple strings * Use print() method rather than println() method * Use ServletOutputStream rather than PrintWriter to send binary data * Initialize the PrintWriter with proper size * Flush the data partly * Minimize code in the synchronized block * Set the content length * Release resources in destroy() method. * Implement getLastModified() method to use browser cache and server cache * Use application server caching facility * Use Mixed session mechanisms such as HttpSession with hidden fields * Remove HttpSession objects explicitly in your program whenever you finish the task * Reduce session time out value as much as possible * Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process. * Disable servlet auto reloading feature. * Use thread pool for your servlet engine and define the size as per application requirement.

11 . How do you optimize a JSP page?

* Use jspInit() method to cache static data * Use StringBuffer rather than using + operator when you concatenate multiple strings * Use print() method rather than println() method * Use ServletOutputStream instead of JSPWriter to send binary data * Initialize the 'out' object (implicit object) with proper size in the page directive. * Flush the data partly * Minimize code in the synchronized block * Set the content length * Release resources in jspDestroy() method. * Give '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 'useBean' action. * Do not use custom tags if you do not have reusability. * Use application server caching facility * Use Mixed session mechanisms such as 'session' with hidden fields * Use 'session' and 'application' as cache. * Use caching tags provided by different organizations like openSymphony.com * Remove 'session' objects explicitly in your program whenever you finish the task

4

Page 5: Performance Issue

* Reduce session time out value as much as possible * Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process. * Disable JSP auto reloading feature. * Use thread pool for your JSP engine and define the size of thread pool as per application requirement.

12 . What are common optimizing practices for EJB?

* Use Local interfaces that are available in EJB2.0 if you deploy both EJB Client and EJB in the same EJB Server. * Use Vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs as Local EJBs if you deploy both EJB Client and EJB in the same EJB Server. * Wrap entity beans with session beans to reduce network calls and to promote declarative transactions. Optionally, make entity beans as local beans where appropriate. * Make coarse grained session and entity beans to reduce network calls. * Control serialization by modifying unnecessary data variables with 'transient' key word to avoid unnecessary data transfer over network. * Cache EJBHome references to avoid JNDI lookup overhead. * Avoid transaction overhead for non-transactional methods of session beans by declaring 'NotSupported' or 'Never' transaction attributes that avoid further propagation of transactions. * Set proper transaction age(time-out) to avoid large transaction. * Use clustering for scalability. * Tune thread count for EJB Server to increase EJB Server capacity. * Choose servlet's HttpSession object rather than Stateful session bean to maintain client state if you don't require component architecture and services of Stateful session bean. * Choose best EJB Server by testing with ECperf tool kit. * Choose normal java object over EJB if you don't want built-in services such as RMI/IIOP, transactions, security, persistence, resource pooling, thread safe, client state etc..

13 . How do you optimize stateless session beans?

* Tune the Stateless session beans pool size to avoid overhead of creation and destruction of beans. * Use setSessionContext() or ejbCreate() method to cache bean specific resources. * Release acquired resources in ejbRemove() method

14 . How do you optimize stateful session beans?

* Tune Stateful session beans cache size to avoid overhead of activation and passivation process. * Set optimal Stateful session bean age(time-out) to avoid resource congestion. * Use 'transient' key word for unnecessary variables of Stateful session bean to avoid serialization overhead. * Remove Stateful session beans explicitly from client using remove() method.

15 . How do you optimize entity beans?

* Tune the entity beans pool size to avoid overhead of creation and destruction of beans. * Tune the entity beans cache size to avoid overhead of activation, passivation and database calls. * Use setEntityContext() method to cache bean specific resources. * Release acquired resources in unSetEntityContext() method * Use Lazy loading to avoid unnecessary pre-loading of child data.

5

Page 6: Performance Issue

* Choose optimal transaction isolation level to avoid blocking of other transactional clients. * Use proper locking strategy. * Make read-only entity beans for read only operations. * Use dirty flag to avoid unchanged buffer data updation. * Commit the data after the transaction completes to reduce database calls in between transaction. * Do bulk updates to reduce database calls. * Use CMP rather than BMP to utilize built-in performance optimization facilities of CMP. * Use ejbHome() methods for global operations. * Tune connection pool size to reduce overhead of creation and destruction of database connections. * Use JDBC tuning techniques in BMP. * Use direct JDBC 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.

16 . How do you optimize message driven beans?

* Tune the Message driven beans pool size to promote concurrent processing of messages. * Use setMesssageDrivenContext() or ejbCreate() method to cache bean specific resources. * Release acquired resources in ejbRemove() method. * Use JMS tuning techniques in Message driven beans.

17 . How do you optimize Java Message Service (JMS)

* Start producer connection after you start consumer. * Use concurrent processing of messages. * Close the Connection when finished. * Choose either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE. * Control transactions by using separate transactional session for transactional messages and non-transactional session for non-transactional messages. * Close session object when finished. * Make Destination with less capacity and send messages accordingly. * Set high Redelivery delay time to reduce network traffic. * Set less Redelivery limit for reducing number of message hits. * Choose non-durable messages wherever appropriate to avoid persistence overhead. * Set optimal message age (TimeToLive value). * Receive messages asynchronously. * Close Producer/Consumer when finished. * Choose message type carefully to avoid unnecessary memory overhead. * Use 'transient' key word for variables of ObjectMessage which need not be transferred.

The Purpose of the Marker InterfaceOne of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.

Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:

- java,lang.Cloneable- java,io.Serializable- java.util.EventListener

6

Page 7: Performance Issue

Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose. For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o: SomeObject o = new SomeObject();SomeObject ref = (SomeObject)(o.clone());If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type "Cloneable." Hence, even though Cloneable is an empty interface, it serves an important purpose.

Hoe to prevent creating more than 2 instances of class?Ans.public class Max2ObjectForClass {

private static int counter = 1;

//Private constructor to ensure that no-one other than this class itself can create the object.private Max2ObjectForClass() {

System.out.println(" inside constructor counter -->"+counter); }

public static Max2ObjectForClass createObject() {Max2ObjectForClass obj;if(counter>2) {

System.out.println("You cannot create more than 2 object");obj = null;

} else {obj = new Max2ObjectForClass();counter++;

}

return obj;}

/** * @param args */public static void main(String[] args) { System.out.println("Hello World!"); Max2ObjectForClass obj1 = Max2ObjectForClass.createObject(); Max2ObjectForClass obj2 = Max2ObjectForClass.createObject(); Max2ObjectForClass obj3 = Max2ObjectForClass.createObject(); Max2ObjectForClass obj4 = Max2ObjectForClass.createObject();

if(obj1 != null) System.out.println("obj1.hashCode() --->"+obj1.hashCode());

if(obj2 != null) System.out.println("obj2.hashCode() --->"+obj2.hashCode());

7

Page 8: Performance Issue

if(obj3 != null) System.out.println("obj3.hashCode() --->"+obj3.hashCode()); if(obj4 != null) System.out.println("obj4.hashCode() --->"+obj4.hashCode());

}

}

Java Singleton Design PatternJava has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications.Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires 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.

Implementing Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor public class SingletonObjectDemo {

// Note that the constructor is privateprivate SingletonObjectDemo() {

// Optional Code}

}Step 2: Create a Method for getting the reference to the Singleton Objectpublic class SingletonObjectDemo {

private static SingletonObject singletonObject;// Note that the constructor is privateprivate SingletonObjectDemo() {

// Optional Code}public static SingletonObjectDemo getSingletonObject() {

if (singletonObject == null) {singletonObject = new SingletonObjectDemo();

}return singletonObject;

}}We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent 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.

8

Page 9: Performance Issue

Step 3: Make the Access method Synchronized to prevent Thread Problems.public static synchronized SingletonObjectDemo getSingletonObject()It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloningWe can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown belowSingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.public Object clone() throws CloneNotSupportedException {throw new CloneNotSupportedException();}The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.class SingletonClass {

private static SingletonClass singletonObject;/** A private Constructor prevents any other class from instantiating. */private SingletonClass() {

// Optional Code}public static synchronized SingletonClass getSingletonObject() {

if (singletonObject == null) {singletonObject = new SingletonClass();

}return singletonObject;

}public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();}

}

public class SingletonObjectDemo {

public static void main(String args[]) {// SingletonClass obj = new SingletonClass();

//Compilation error not allowedSingletonClass obj = SingletonClass.getSingletonObject();// Your Business LogicSystem.out.println("Singleton object obtained");

}}

Another approachWe don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.public class SingletonClass {

private static SingletonClass ourInstance = new SingletonClass();

9

Page 10: Performance Issue

public static SingletonClass getInstance() {

return singletonObj;}private SingletonClass() {}

}In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence 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 object?

There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:

1. Using new keywordThis is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.

MyObject object = new MyObject();

2. Using Class.forName()If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

 3. Using clone()The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();MyObject object = anotherObject.clone();

4. Using object deserializationObject deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );MyObject object = (MyObject) inStream.readObject();

Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

this.getClass().getClassLoader().loadClass(”com.amar.myobject”).newInstance();

10