Update (comments from users@tomcat.apache.org mailing list):
Wednesday, May 16, 2012
Update (comments from users@tomcat.apache.org mailing list):
Wednesday, May 9, 2012
J2EE Performace Tips
Small optimizations (like turning logging down) can yield huge gains, whereas others can have minuscule effects. The key to tackling bottlenecks is to prioritize and focus on the areas of your code that will yield the biggest return for your time investment. Focus 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.
You can scale your system to satisfy an increased load by using vertical and horizontal scaling techniques (software and hardware), but not always. Sometimes you can't use these techniques because either the budget is tight, time is limited, or your system has inherent architectural limitations. In lieu of adding more hardware, distributing your code, or adding more servers, you can use the following server-side strategies to improve the performance of a single J2EE/EJB application.
Consolidate your search queries into a single JDBC call using a DataAccessObject (DAO) or FastLaneReader (Marinescu/J2EE Blueprints).
However, for batch processes, the goal is to achieve high throughput so the job finishes as quickly as possible. Parallel processing can aid this. Spawn threads outside the container and divvy up the load into small units of work that are capable of being executed concurrently. Use threads to spread the load. Don't spawn more threads than the server can handle. Keep the number of client threads to fewer than the containers thread pool limit.
Entity beans provide an abstraction layer between the higher-level business components and the database. When a developer makes a call to a method on a bean, he or she doesn't see what happens under the covers because it's transparent. The developer can assemble large objects or data structures using many entity calls. He or she can be oblivious to the expensive low-level database I/O taking place. One way to alleviate this bottleneck is to replace your critical sections with specialized pieces of pure JDBC code that are optimized for the task. DataAccessObjects (DAOs) and FastLaneReaders (Marinescu/J2EE Blueprints) are common techniques for accelerating reads. These patterns give you fine-grained control over your queries for efficient read access. A DAO can be used to consolidate many DBMS requests made by an entity bean (finder + loads) into a single JDBC call. DAOs are useful for supporting search screens or requests over data that span multiple beans and/or database tables.
- Use your DAO to
query for data directly from the DBMS rather than via your entity beans.
Session beans and other components can call your DAO directly.
- Design your DAO
so that it can be tailored to return only what you need.
- Design your DAO
so that it can limit the number of rows returned.
- Use finally
clauses to ensure that all JDBC resources are closed when you're finished
with them. This ensures that you don't hog or consume connections and
cursors.
- Query against
DBMS views to make your DAOs more reusable and portable. If you need to
make a change to a query, make a change to the view instead.
- 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
- Row limiting
(The Statement and ResultSet classes provide methods (setMaxRows() and
setFetchSize()) to limit the number of rows returned and set hints for
ResultSet fetch sizes.)
As part of your DAO design, you must decide in which form the data should be returned and how it should be converted. In some cases, you may want to return loosely typed collections such as Lists or Maps, and in other cases you may want to immediately convert ResultSet data into strongly typed Java objects relevant to your system. One way to handle this at the DAO level is to use a helper ResultSetConverter interface. This interface is responsible for converting RowSets into strongly typed application object types or collections. The DAO uses it to automatically convert ResultSet data into your target object(s):
public interfaceResultSetConverter {
publicObject toObject(ResultSet rs)throwsException;
}
Create
a simple ResultSet to Map Converter class by implementing the ResultSetConverter
interface. Inside the toObject() method, pull the data from the result set and
place it into a map of column name/value pairs. The map is returned to the DAO
to be passed back to the DAO caller:
classMapConverterimplementsResultSetConverter {
publicObject toObject(ResultSet rs)throwsException {
Map map =newHashMap();
ResultSetMetaData meta = rs.getMetaData();
// Load ResultSet into map by column name
intnumberOfColumns = meta.getColumnCount();
for(inti = 1; i <= numberOfColumns; ++i) {
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
// place into map
map.put(name, value);
}
returnmap;
}
}
To
use your DAO and converter, acquire a DAO instance and invoke the query()
method to execute your SQL. Use the rowLimit parameter to limit the number of
rows returned and pass in the converter class for the DAO to use.
DAO dao = DAO.get();
// Create our own converter for getting the first column as a String
ResultSetConverter myConverter = new ResultSetConverter() {
public Object toObject(ResultSet rs) throws Exception {
return rs.getString(1);
}
};
// Execute a query against a VIEW,
limit the number of rows returned to 10 and use myConverter to convert the results
List data = dao.query("myView", 10, myConverter);
// Do something with the data, ship to the JSP etc.
The J2EE Performance-tuning Trade-offExperienced practitioners know that when addressing J2EE application performance issues, there are no silver bullets. Performance tuning is a trade-off between architecture concerns, such as flexibility and maintainability. Performance increases are won by combining different techniques, patterns, and strategies.
And if all else fails, you can hope that that extra-fast machine you ordered turns up sooner rather than later. :)
- Symptoms of network problems include slow response times, excessive database table scans, database deadlocks, pages not available, memory leaks and high CPU usage.
- Causes of performance problems can include the application design, incorrect database tuning, internal and external network bottlenecks, undersized or non-performing hardware or Web and application server configuration errors.
- Root causes of performance problems come equally from four main areas: databases, Web servers, application servers and the network, with each area typically causing about a quarter of the problems.
- The most common database problems are insufficient indexing, fragmented databases, out-of-date statistics and faulty application design. Solutions include tuning the index, compacting the database, updating the database and rewriting the application so that the database server controls the query process.
- The most common network problems are undersized, misconfigured or incompatible routers, switches, firewalls and load balancers, and inadequate bandwidth somewhere along he communication route.
- The most common application server problems are poor cache management, unoptimized database queries, incorrect software configuration and poor concurrent handling of client requests.
- The most common web server problems are poor design algorithms, incorrect configurations, poorly written code, memory problems and overloaded CPUs.
- Having a testing environment that mirrors the expected real-world environment is very important in achieving good performance.
- The deployed system needs to be tested and continually monitored.
- Use the servlet init() method to cache static data, and release them in the destroy() method.
- Use StringBuffer rather than using + operator when you concatenate multiple strings.
- Use the print() method rather than the println() method.
- Use a ServletOutputStream rather than a PrintWriter to send binary data.
- Initialize the PrintWriter with the optimal size for pages you write.
- Flush the data in sections so that the user can see partial pages more quickly.
- Minimize the synchronized block in the service method.
- Implement the getLastModified() method to use the browser cache and the server cache.
- Use the application server's caching facility.
- Session mechanisms from fastest to slowest are: HttpSession, Hidden fields, Cookies, URL rewriting, the persistency mechanism.
- Remove HttpSession objects explicitly in your program whenever you finish the session.
- Set the session time-out value as low as possible.
- Use transient variables to reduce serialization overheads.
- Disable the servlet auto reloading feature.
- Tune the thread pool size.
- Thoroughly test any framework in a production-like environment to ensure that stability and performance requirements are met.
- Each component should be thoroughly reviewed and tested for its performance and security characteristics.
- Using the underlying EJB container to manage complex aspects such as transactions, security, and remote communication comes with the price of additional processing overhead.
- To ensure good performance use experienced J2EE builders and use proven design patterns.
- Consider the impact of session size on performance.
- Avoid the following common mistakes: Failure to close JDBC result sets, statements, and connections; Failure to remove unused stateful session beans; Failure to invalidate HttpSession.
- Performance requirements include: the required response times for end users; the perceived steady state and peak user loads; the average and peak amount of data transferred per Web request; the expected growth in user load over the next 12 months.
- Note that peak user loads are the number of concurrent sessions being managed by the application server, not the number of possible users using the system.
- Applications that perform very little work can typically handle many users for a given amount of hardware, but can scale poorly as they spend a large percentage of time waiting for shared resources.
- Applications that perform a great number of computations tend to require much more hardware per user, but can scale much better than those performing a small number of computations.
- A scalable server application probably needs to be balanced across multiple JVMs (possibly pseudo-JVMs, i.e. multiple logical JVMs running in the same process).
- Performance of an application server hinges on caching, load balancing, fault tolerance, and clustering.
- Application server caching should include web-page caches and data access caches. Other caches include caching servers which "guard" the application server, intercepting requests and either returning those that do not need to go to the server, or rejecting or delaying those that may overload the app server.
- Application servers should use connection pooling and database caching to minimize connection overheads and round-trips.
- Using one thread per user can become a bottleneck if there are a large number of concurrent users.
- The (open source) OSCache tag library provides fast in-memory caching.
- Cache pages or page sections for a set length of time, rather than update the page (section) with each request.
- Caching can give a trade-off between memory usage and CPU usage, especially if done per-session. This trade-off must be balanced correctly for optimal performance.
- Separate the UI controller logic from the servlet business logic, and let the controllers be mobile so they can execute on the client if possible.
- Validate data as close to the data entry point as possible, preferably on the client. This reduces the network and server load. Business workflow rules should be on the server (or further back than the front-end).
- You can use invisible applets in a browser to validate data on the client.
Wednesday, July 28, 2010
Project Management Case Studies
Case Studies
The following case studies show the use of project management in practice. Studying real-life situations will help you see how others have been successful.
If you have a case study you think would be of interest to people managing projects, please let us know and we'll be happy to consider it for publication.
Every Beginning is Difficult
New undertakings or experiences are always challenging at first. This is no different when Schenker Singapore (Pte) Ltd, a transport and logistics company decided to embark on something new - a Lean Six Sigma programme. It might seem to be even more demanding at the outset since the number of 3rd party logistics providers rising to this challenge is limited. Best practices in this industry are not widespread and hard to come by. This is the story of what happened.
Project Management Approach for Business Process Improvement
Business process improvement initiatives are frequently key projects within an organisation, regardless of the size of the organisation or, frankly, the size of the business process improvement initiative. Even if a business process improvement initiative is targeted at an individual department, the impact of the change will be organisation-wide.
The Best Project Managers are Emotion-driven Leaders
Charles J. Pellerin's own personal ill-fated story, as the project director for the launch of the Hubble telescope, on his journey to the discovery of true leadership. This journey not only got him to redeem himself through an officially 'unauthorised' 60M US$ fix mission to get astronauts to repair the telescope, but also got him to better understand the root of true leadership and design a system to make it happen.
Using ROI to Evaluate Project Management Training
Return on Investment (ROI) is a monetary measurement that is used to evaluate the efficiency and effectiveness of an investment made by an organisation. Investments take many forms, financial, human capital, equipment, and training programmes, to name just a few. This article will focus on the use of ROI and the Phillips ROI Methodology to measure the effectiveness of a project management training programme completed within XYZ Law Firm.
The Hidden Costs and Dangers of the Shortcut
We live in a world where we are often pressured to take shortcuts to save time and cut costs as much as possible. However, if you're not a skilled and experienced project manager, the wrong shortcut could end up costing you a lot more. Here's an anecdote to think about.
Corporate Social Responsibility (CSR) and Project Management
Corporations are more sensitive to social issues and image than ever before. This sensitivity has given rise to CSR initiatives, but the question is: "How do I rationalise the organisation's demands for CSR with my project's objectives?" While there are no easy answers to this question, this article uses actual examples to point out what to avoid and offers tips and tricks on how to rationalise CSR and project objectives.
Green Projects
More and more emphasis is being placed on projects that help our environment, or are at least compatible with the environment. These projects are commonly referred to as "green" projects. Whether "greening" is an adjunct to the project, or a project objective more and more projects are initiated that can be called "green." Green projects place new demands on the project manager. This article describes one such project and some of these new demands.
Project Failures From the Top Down: Can Marchionne Save Chrysler
On the surface the merger between Fiat and Chrysler is very promising, but a bit of history on Chrysler and Marchionne's management style suggests that the sustainability of the merger might be in trouble. Will Chrysler be revived? Can they initiate the kind projects that will return it profitability, or is Chrysler headed for a fatal crash?
Communication is Key: Getting Everyone in the Loop
Are you finding that the communication among your staff, across different departments, and with your vendors is often inefficient and even quite redundant? How many times have you answered the same question either by e-mail or with a phone call? Do you find that inaccurate information is being passed on to customers because sales or services people are referring to outdated e-mails or an implementation schedule that has changed? Does each one of your teams have its own file system and database and use many interfaces to organise its information?
A Tale of Two Projects
A business tale of what it takes to turn around troubled projects. The year is 2005 and times are good. The business environment is vibrant and the economy is strong. Large businesses are committing large amounts of capital and resources to implement new strategies, establish new capabilities, and open new markets. It was no different at PintCo, where Jack works as a Director of Customer Relationship Management.
How Gantt Charts Can Help Avoid Disaster
A short case study about the importance of using appropriate tools, such as Gantt charts, when managing time sensitive projects. Having run 15 months late on completion of a construction project, a building company incurred extensive penalty charges, which eventually led to its closure. Not having any project Gantt charts indirectly led to the company's failure.
NASA Project Management Challenge 2008
One of the first major uses of project management as we know it today was to manage the United States space programme. It started with the inauguration speech in 1961 of John F. Kennedy when he said, "I believe that this nation should commit itself to achieving the goal, before this decade is out, of landing a man on the moon and returning him safely to the earth." In 1986 the Challenger space shuttle disaster focused attention on risk management, group dynamics and quality management. Today NASA continues to focus on project management best practice to deliver major aerospace projects costing many billions of dollars.
Rescuing a Small Project
Project Management. Recently I was asked to jump in and rescue a small infrastructure project that was headed for disaster. What did I do?