Wednesday, August 5, 2009

Tuning Performance of Java Web Application

source: http://java-junction.blogspot.com/search/label/Performance%20Tuning

Best Practices to improve performance in Servlets

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

Best Practices to improve Performance in JSP

1. Use jspInit() method to cache static data
2. Use StringBuffer rather than using + operator when you concatenate multiple strings
3. Use print() method rather than println() method
4. Use ServletOutputStream instead of JSPWriter to send binary data
5. Initialize the 'out' object (implicit object) with proper size in the page directive.
6. Flush the data partly
7. Minimize code in the synchronized block
8. Set the content length
9. Release resources in jspDestroy() method.
10. Give 'false' value to the session in the page directive to avoid session object creation.
11. Use include directive instead of include action when you want to include the child page content in the translation phase.
12. Avoid giving unnecessary scope in the 'useBean' action.
13. Do not use custom tags if you do not have reusability.
14. Use application server caching facility
15. Use Mixed session mechanisms such as 'session' with hidden fields
16. Use 'session' and 'application' as cache.
17. Use caching tags provided by different organizations like openSymphony.com
18. Remove 'session' objects explicitly in your program whenever you finish the task
19. Reduce session time out value as much as possible
20. Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
21. Disable JSP auto reloading feature.
22. Use thread pool for your JSP engine and define the size of thread pool as per application requirement.

Best practices to improve performance in JDBC

1. Get database connection from connection pool rather than getting it directly
2. Use batch transactions.
3. 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.
4. Your database server may not support all isolation levels, be aware of your database server features.
5. Use PreparedStatement when you execute the same statement more than once.
6. Use CallableStatement when you want result from multiple and complex statements for a single request.
7. Use batch update facility available in Statements.
8. Use batch retrieval facility available in Statements or ResultSet.
9. Set up proper direction for processing rows.
10. Use proper getXXX () methods.
11. Close ResultSet, Statement and Connection whenever you finish your work with them.
12. Write precise SQL queries.
13. Cache read-only and read-mostly tables data.

Performance improvement techniques in Object creation

1. Avoid creating objects in a loop.
2. Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
3. Whenever you are done with an object make that reference null so that it is eligible for garbage collection.
4. Never keep inheriting chains long since it involves calling all the parent constructors all along the chain until the constructor for java.lang.Object is reached.
5. Use primitive data types rather than using wrapper classes.
6. Whenever possible avoid using class variables, use local variables since accessing local variables is faster than accessing class variables.
7. Another technique is Lazy object creation: i.e. delaying the memory allocation to an object till it is not being put into use. This way a lot of memory is saved till the object is actually put in to use.
Performance improvement techniques in Exceptions
1. In a catch block avoid using the generic class Exception. For each try block use specific catch blocks based on what can go wrong in your code.
2. Whenever you are using a throws clause always use the specific subclass of Exception like FileNotFoundException rather than using throws Exception.
3. Always use the finally block to release the resources like a database connection, closing a file or socket connection etc. This prevents resource leaks even if an exception occurs.
4. Do not use Exception handling in loops. It is better to place loops inside try/catch blocks than vice versa. Here is an code snippet that gives bench mark.

Performance improvement techniques in loops

1. Always use an int data type as the loop index variable whenever possible because it is efficient when compared to using byte or short data types. because when we use byte or short data type as the loop index variable they involve implicit type cast to int data type.
2. When using arrays it is always efficient to copy arrays using System.arraycopy() than using a loop.
3. Always avoid anything that can be done outside of the loop like method calls, assigning values to variables, or testing for conditions.
4. Method calls are very costly and you only make it worse by putting them in a loop. So as far as possible avoid method calls in a loop.
5. It is better to avoid accessing array elements in a loop the better option would be to use a temporary variables inside the loop and modify the array values out of the loop. It is fast to use a variable in a loop than accessing an array element.
6. Try to compare the terminating condition with zero if you use non-JIT or HotSpot virtual machine, here is an example to prove the point. JIT or HotSpot virtual machines are optimized for general loops so you do not have to bother about the terminating condition.

Reference: www.precisejava.com


Tips For Measuring Application Performance

Here are some of important points which should be considered while measuring application performance.

- Test systems should match production as closely as possible. Same hardware, OS, and software.
- Populate databases with the number of records expected in production.
An application may perform well with a small number of records in the database. Performance could degrade a great deal as the number of records in the table(s) increases
- Test HTTP requests with different request parameters.
Test with the extremes. A page which performs a search may perform well when the search criteria returns a small result set, but perform poorly when the search criteria returns a large result set.
- Simulate expected traffic over time including short term spikes.
A page which performs well with low request volume can cause the server to fail under higher request volume.
- Use Server load testing tools (like Apache Jakarta JMeter) to simulate heavy load.


Tomcat - Jboss Performance Tuning Tips

Apache Tomcat is an implmentation of the Java Servlet and JavaServer Pages technologies.
In production Enviroment, number of resources which can all impact application overall performance. Here are some important point which can help to improve Tomcat Performance.

Performance Tuning - Tomcat Configuration

Configure server.xml parameters as following.

-Set reloadable to false

When reloadable is true Tomcat tries to detect web application class changes and automatically reload any classes which change. Setting this to false removes a lot of unnecessary overhead in production.

-Set liveDeploy to false

liveDeploy controls whether your webapps directory is periodically checked for new web application directories and war files. This is done using a background thread. Set this to false and use the manager application or ant deploy tasks instead.

-Set debug to 0

Disable all debug output, unnecessary logging just adds overhead.

-Set swallowOutput to true

This makes sure all output to stdout or stderr for a web application gets directed to the web application log rather than the console or catalina.out. This makes it easier to troubleshoot web application problems.


Performance Tuning - Jasper 2 Configuration

Configure web.xml parameters as following.

-Set development to false

Disables JSP page out of date checks on each request and enables JSP background recompiles. development is set to true by default.

-Use JSP custom tag pooling

Object pooling of classes which implement custom tags significantly improves performance of JSP pages which use custom tag libraries. JSP custom tag pooling is enabled by default.

-Configure Jasper to fork javac compiles. (Do not set fork to true on MS Windows)

The JVM compiler javac has known memory leaks. Eliminates JVM memory usage and GC overhead of javac by configuring Jasper to fork javac when compiling JSP pages.

No comments: