Performance Tuning

Performance tuning servlets requires a slightly different mindset than performance tuning normal Java applications or applets. The reason is that the JVM running the servlets is expected to simultaneously handle dozens, if not hundreds, of threads, each executing a servlet. These coexisting servlets have to share the resources of the JVM in a way that normal applications do not. The traditional performance-tuning tricks still apply, of course, but they have a different impact when used in a heavily multithreaded system. What follows are some of the tricks that have the largest special impact on servlet developers.

Go Forth, but Don’t Prosper

Avoid the unnecessary creation of objects. This has always been good advice—creating unnecessary objects wastes memory and wastes a fair amount of time as the objects are created. With servlets, it’s even better advice. All but the most recent JVMs have a global object heap that must be locked for each new memory allocation. While any servlet is creating a new object or allocating additional memory, no other servlet can do so.

Don’t Append by Concatenation

Avoid concatenating several strings together. Use the append() method of StringBuffer instead. This too has always been good advice, but with servlets it’s particularly tempting to write code like this to prepare a string for later output:

String output;
output += "<TITLE>";
output += "Hello, " + user;
output += "</TITLE>";

Although this code looks nice and neat, when it runs ...

Get Java Servlet Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.