I need to synchronize a mysql query, so just one user can access the specified part at the same time. I tried synchronized(){}
, but this doesn't work. The users can access the method simultaneously. It's a jsp webapplication using tomcat6. I need this, because the webserver crashes when too many user run the query at the same time.
String sql = "SELECT * FROM products;"
ResultSet rs;
//This block should be synchronized
Statement s = con.createStatement();
rs = s.excecuteQuery(sql);
while (rs.next()) {
// do some stuff..
}
Thanks for any help.
Edit: how I tried to synchronize
public class connect {
public static String URL = "url";
public static String USER = "root";
public static String PASSWORD = "password";
private Object lock = new Object();
public void getData() {
Connection con;
try {
con = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "SELECT * FROM products;";
ResultSet rs;
//This block should be synchronized
synchronized(lock) {
Statement s = con.createStatement();
rs = s.executeQuery(sql);
while (rs.next()) {
// do some stuff..
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I think the object lock
should be stored on the server. But what's the right way to do this?