There are many questions on thread safety of servlets, but I want to ask about the other classes that servlet uses.
In a normal application the servlet classes uses other normal classes also (my appl do) like in MVC. So my question is should I declare all the functions in my model classes as synchronized
Suppose I have 2 servlets and the use classes Dog and Cat. Both classes have some static and non static functions and static and non static variables.
these methods uses database connection to display contents, and I got nullpointerexception
for this code
try {
Connection con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement();
select = "SELECT * FROM table";
java.sql.ResultSet result = stmt.executeQuery(select);
while(result.next())
{
do something
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
if (con != null)
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
and to my surprise i get the exception in line try { con.close(); } : nullPointerException
To my understanding since I have already checked that if (con != null)
so con
should
not be null.
So,
In a servlet, it is generally poor design ... and possibly a mistake ... to have static variables. But if you do use (and need to use) static variables, then the code that accesses and updates them would need to be properly synchronized. (Servlet code is executed on multiple threads ... unless you hobble the web container framework by configuring only one worker thread.)
Declaring the methods as synchronized
is one way to achieve this, if you do it properly.
However ...
Simply declaring methods to be synchronized
willy-nilly is a bad idea. You need to understand the anticipated concurrency patterns of your code before you start adding the synchronization. Mindless addition of synchronized
can lead to concurrency bottlenecks, and potential deadlocks. (And you can still have thread-safety issues ... if the granularity of mutual exclusion is not right for the problem.)
I concur with @Roman C's Answer. You should NOT be attempting to share the same database connection across multiple requests ... if that is what you are actually doing. I suggest you look into use a database connection pool.