Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
    Bookmark Topic Watch Topic
  • New Topic

Sharing Static Objects  RSS feed

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.


Posts: 5167
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Report post to moderator
Double post
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!