Java Performance Tuning
Java(TM) - see bottom of page
Our valued sponsors who help make this site possible
JProfiler: Get rid of your performance problems and memory leaks!
Training online: Concurrency, Threading, GC, Advanced Java and more ...
Tips January 2004
JProfiler
|
Get rid of your performance problems and memory leaks!
|
JProfiler
|
Get rid of your performance problems and memory leaks!
|
|
|
Back to newsletter 038 contents
http://www.devx.com/Java/Article/18100
J2EE Design Strategies That Boost Performance (Page last updated December 2003, Added 2004-01-27, Author Lara D'Abreo, Publisher devX). Tips:
- Design with Performance in Mind: Understand the number of concurrent users, target response times, usage patterns, and data growth, which parts of the system are session-based and which are non-session or batch-based.
- Performance bottlenecks must be systematically identified and solved. The later in the development life cycle you address them, the more expensive they become to fix.
- Small optimizations (like turning logging down) can yield huge gains, whereas others can have minuscule effects: prioritize and focus on the areas of your code that will yield the biggest return for your time investment.
- Focus performance tuning on frequently used parts of the code, the parts critical to your business.
- Gather accurate performance metrics and use repeatable test cases to validate against your performance targets.
- Align your DBMS access to support your usage patterns. Queries should return only the one piece of data that you need.
- Search queries that use finders can take a long time to run.
- Call the DBMS with one bulk query rather than issue a series of smaller requests.
- Use DataAccessObject or FastLaneReader patterns to optimize queries.
- For large query results use pagination.
- Use built-in database features that may help reduce query times, such as stored procedures, indexes, views, and table caches.
- Reduce the number of redundant reads by caching.
- Pass information around as method parameters or consider caching it on the session or thread context.
- Data that changes infrequently, such as meta data or configuration data, is good for caching.
- Break up long-lived transactions into multiple shorter, more-reliable chunks.
- Combine multiple short-lived transactions to optimize transaction throughput.
- Adjust the number of records processed in one transaction so that you get optimum throughput for your request.
- Spawn threads outside the container to parallel process small units of work that are capable of being executed concurrently. Don't spawn more threads than the server can handle.
- Keep the number of client threads to fewer than the containers thread pool limit.
- Structure your components so that they are thread-safe and can work concurrently, avoiding DBMS contention.
- Divide your units of work up so that they operate over different data sets.
- If your on-line response time is slow, reduce the amount of work performed during the request and defer expensive or non-essential functions to later.
- Store work temporarily in holding tables or execute it asynchronously using JMS.
- Components that don't have strict real-time requirements, such as data-extraction programs, collation and sorting routines, file import/export, etc., can be performed off-line as batch processes.
- Use session beans and remote interfaces sparingly to minimize request overheads and streamline your code.
- Design your DataAccessObject so that it can be tailored to return only what you need.
- Design your DataAccessObject so that it can limit the number of rows returned.
- Use PreparedStatements to pre-compile frequently executed SQL statements.
- Batch methods on the Statement class (addBatch() and exectuteBatch()) to batch up multiple SQL calls into one hit to the database.
- Limit the size of the result set batches using the Statement and ResultSet classes methods setMaxRows() and setFetchSize().
- Performance tuning is a trade-off between architecture concerns, such as flexibility and maintainability.
- If all else fails, use a faster machine [actually that could be the cheapest option if it works].
http://java.sun.com/developer/JDCTechTips/2003/tt1208.html
Multithreading in Swing & ThreadLocal Variables (Page last updated December 2003, Added 2004-01-27, Author John Zukowski, Publisher Sun). Tips:
- For thread safe code (i.e to avoid deadlocks), run show(), setVisible(), pack() and other methods which create peers in the event dispatch thread, e.g. EventQueue.invokeLater(new Runnable{ public void run() { frame.show(); } });
- Use ThreadLocal or InheritableThreadLocal objects to manipulate data that should have thread scope.
http://www.devx.com/webdev/Article/17950
Load Testing with Apache JMeter Kulvir (Page last updated December 2003, Added 2004-01-27, Author Singh Bhogal, Publisher DevX). Tips:
- To gain a quantitative insight as to what your site can handle, you need a way to simulate and analyze different load scenarios.
- Use Apache Jmeter to perform fast, easy load testing on your Web pages, Web applications, and databases.
- Make sure you run performance tests before and after any optimizations are made to determine whether you have in fact made any improvement.
- Running performance tests in a development environment that differs from your production environment can often be a misleading and misdirected effort.
http://www-106.ibm.com/developerworks/xml/library/x-tipstx2/
Parsing XML documents partially with StAX (Page last updated December 2003, Added 2004-01-27, Author Berthold Daum, Publisher IBM). Tips:
- StAX allows you to skip certain event classes by implementing an event filter.
http://www-106.ibm.com/developerworks/apps/transform.wss?URL=/developerworks/websphere/library/bestpractices/httpsession_performance_serialization.xml&xslURL=/developerworks/websphere/xsl/bestpractice.xsl
Improving HttpSession Performance with Smart Serialization (Page last updated December 2003, Added 2004-01-27, Authors Kyle Brown, Keys Botzum, Publisher IBM). Tips:
- Storing too much session state leads to performance problems in storing large session objects
- Storing too little session state leads to performance problems when developers must constantly re-create the same set of objects (and can adversely affect the functionality of an application)
- There are three basic approaches to keeping session state valid across multiple clustered application servers: Store session objects in a shared database; Synchronize in-memory sessions using a notification mechanism like JMS; Use session affinity to pin users to a particular application server instance.
- If using shared or replicated sessions, it can take a long time to serialize a large session object.
- Only serialize updates, and never read serialized objects from a database if you can avoid it.
- We have always recommended that the session be kept to a small size, typically under 2K.
- Hold a cache element key in the session, and keep large data in a separate cache.
- An efficient way to cache large data in HttpSession is use a Serializable object to hold that data, making sure that the data is held using
transiet
data variables. Only key data (for database retreival or other required to reconstruct the cache) should be non-transiet
.
- Since failover is rare, session data in transient fields are rarely reloaded.
- Use lazy instantiation techniques so that user data that is not read by the application is never fetched from the back end.
- Another alternative to string large amounts of session data is the use of a custom session state storage mechanism, such as keeping all session state in a database table specific to the application, and writing customized and tuned SQL code to store and retrieve the entire session state.
http://www.developer.com/java/other/article.php/3286861
Java Sound, Compressing Audio with mu-Law Encoding (Page last updated December 2003, Added 2004-01-27, Author Richard G. Baldwin, Publisher developer.com). Tips:
- CD quality music is sampled at 44.1 KHz using 16 bit words or 705,600 bits for each second of sound. That would mean that 1 second of uncompressed CD quality music would require almost a 1 Megabit bandwidth to transfer in real time, and also implies large storage requirements. Hence the need for compression.
- Mu-law (also "u-law") encoding is a form of logarithmic quantization or companding. It's based on the observation that many signals are statistically more likely to be near a low signal level than a high signal level. Therefore, it makes more sense to have more quantization points near a low level than a high level.
- To convert from analog to compressed digital, you can reduce the number of samples used to describe the analog signal, and reduce the number of bits used to describe each sample.
- Compression algorithms designed for the data are usually more efficient; for example scanning a black and white picture with an algorithm designed to maintain colors produces a large amount of redundant data.
- mu-law encoding and compression is apparently adequate for the storage and transmission of spoken voice signals in many cases.
- The primary advantage of mu-law encoding over simple truncation is that mu-law encoding maintains significantly greater dynamic range while keeping information loss within tolerable limits.
http://www.informit.com/isapi/guide~java/seq_id~63/guide/content.asp
Java performace tuning (Page last updated December 2003, Added 2004-01-27, Author Steven Haines, Publisher informIT). Tips:
- When analyzing alorithms, look at three distinct values: The Best-case Time; The Average-case Time; The Worst-case Time. In most cases, you are concerned with the worst-case time.
- [Article discusses big-Oh notation and beaviours].
- Carefully examine your code and try to remove as many loops and more importantly inner loops as you can.
- HashSet performs mutator methods in constant time; TreeSet performs these methods in O( log N ) time.
- ArrayList and Vector are growable arrays that provide constant time random access to its elements.
- If you are running single threaded code against a List, then ArrayList should have better performance than Vector.
http://www.onjava.com/pub/a/onjava/2003/04/02/multiple_submits.html
Handling Multiple Submits (Page last updated April 2003, Added 2004-01-27, Author Al Saganich, Publisher OnJava). Tips:
- The primary and most effective way to handle the multiple submits problem is to prevent it from happening. For example, a small amount of JavaScript embedded in a browser page can remember if the submit button was previously pressed and on a resubmit, an alert pops up and the form is not submitted again. Unfortunately, client-side validation like this can be easily circumvented by accident (and on purpose).
- Be careful of using HttpSession.getSession(true), as a denial-of-service attack can be allowed by always creating new sessions on demand. An unscrupulous user could discover your site was creating sessions and flood it with new session requests. Instead use getSession(false) and then redirect to a login page when a session is not detected to protect against such an attack.
- Testing for the existence or non-existence of a session, and acting accordingly can let you avoid repeatedly handling multiple submits.
Jack Shirazi
Back to newsletter 038 contents
Last Updated: 2025-01-27
Copyright © 2000-2025 Fasterj.com. All Rights Reserved.
All trademarks and registered trademarks appearing on JavaPerformanceTuning.com are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. JavaPerformanceTuning.com is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
URL: http://www.JavaPerformanceTuning.com/news/newtips038.shtml
RSS Feed: http://www.JavaPerformanceTuning.com/newsletters.rss
Trouble with this page? Please contact us