Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
    Bookmark Topic Watch Topic
  • New Topic

Sharing Static Objects

Sanjeev BhimaRao
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Report post to moderator

I have a question of sharing DB Connection object across different servlets of the same webapp.

The current design is as follows.

Class 1 provides methods to connect to DB.
Methods of Class 1 are not static. (For each query it does a new con.createStatement()).

Class 2, 3, 4 etc declare static instance of Class 1.
During servlet context initialization - the static instance of Class 1 is initialized to new Object.
And both doPost() and doGet() of Classes 2,3 and 4 use the above created instance.

I have the following doubts.
1. how this will work if the application is scaled (when multiple servlet instances are created by the container)
2. how the single static object will be shared by the different servlet instances.
3. When the same servlet handles two different requests like GET and POST at the same time, how to ensure that something bad does not happen with the Class 1 instance.

Should I synchronize the methods of Class 1?

Kindly advice.


Darryl Burke
Posts: 5149
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Report post to moderator
Double post
    Bookmark Topic Watch Topic
  • New Topic