A singleton lifespan in Tomcat

A

Alexandre Brizard

Hi!

I have a singleton class that operates on a Tomcat server. When I
start Tomcat, everything is fine, I have only one instance of the
class. But, if I modify the web.xml file, per example, and the context
is stopped then restarted, the instance I had in the first place isn't
destroyed and continues to run, and another singleton is created when I
call the getInstance() method of the singleton. How do I fix that?

Here are some excerpts of my class:

public class ConnectionPool {

private static ConnectionPool instance = null;
..
..
..
public synchronized static ConnectionPool getInstance()
throws SQLException, ClassNotFoundException {
if (instance == null){
instance = new
ConnectionPool(m_driverName,m_dbURL,m_user,m_password);
}
return instance;
}
..
..
..
};

Thanks!
 
C

Chris Smith

Alexandre Brizard said:
I have a singleton class that operates on a Tomcat server. When I
start Tomcat, everything is fine, I have only one instance of the
class. But, if I modify the web.xml file, per example, and the context
is stopped then restarted, the instance I had in the first place isn't
destroyed and continues to run, and another singleton is created when I
call the getInstance() method of the singleton. How do I fix that?

Both of the basic singleton implementations in Java rely on the
uniqueness of static variables. When you load a new web application in
Tomcat (including if you modify a file that convinces Tomcat to reload
your web app for you), Tomcat will create a new servlet context class
loader, and the new class loader will load new classes that have their
own static variables.

Since the new web application will not have access to the old instance,
you need to swap over to the new instance. That probably means properly
closing your old instance when you're finished with it. Try adding a
listener to the servlet context to do that.

Google turns this up:

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,226
Latest member
KristanTal

Latest Threads

Top