Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Once said this, the patterns to be included here will be those that, although being safe and legal on a standalone application, need to be refactored to make them "compatible" with the servlet container.

Threads

No other threads started in the servlet must run. Otherwise they keep local variables, their classes and the whole class loader hard referenced.

DriverManager

If you load a java.sql.Driver in your own classloader (or servlets), the driver should be removed before undeploying. Each driver is registered in DriverManager which is loaded in system classloader and references the local driver.

No Format

                Enumeration<Driver> drivers = DriverManager.getDrivers();
		ArrayList<Driver> driversToUnload=new ArrayList<Driver>();
		while (drivers.hasMoreElements()) {
			Driver driver = drivers.nextElement();
			if (driver.getClass().getClassLoader().equals(getClass().getClassLoader())) {
				driversToUnload.add(driver);
			}
		}
		for (Driver driver : driversToUnload) {
	            DriverManager.deregisterDriver(driver);
                }

The Singleton Pattern

This is a VERY used pattern in many java programs. It works safe and sound in any standalone application, and it looks something like:

...

Many of the workarounds below will sacrifice some of the virtues of the original pattern, for the sake of the server integrity. It is up to the designer/developer to decide whether these sacrifices are worth the benefits.

Validation

Before you refactor your whole application, please ensure if this is really the problem. My singletons are definitely removed, but tomcat keeps crashing.

  1. Override method finalize in such a singleton class and put a System.out.println()-Message. 2. In the constructor call several time System.gc() (because the garbage collector is a little bit lazy) 3. Redeploy the application several times 4. Probably you will see that the old singletons are definitely finalized which is only the case if the class loader is garbage collected. 5. After several redeployments an out of memory occures, even with one or two "singletons" in memory.

Workaround 1: Move the class to another classloader

...