Related to the question: Java Threading with MYSQL puzzled
The counter int, is synchronized, the function calls to executeQuery are not synchronized. Results I am getting
counter: 1
row from MYSQL: 1
counter: 2
row from MYSQL: 1
counter: 3
row from MYSQL: 1
Expected Output-> row from MYSQL: should be the same as counter
All the threads run at the same time the first query. Hence they get the same id of the result. However they synchronize for the counter iteration. To me this is absurd. Is this behavior documented? How can I bypass it? Verifier.java
public void run() {
int id = 0;
String query = "SELECT ID_num FROM Searches WHERE checked='0'";
ResultSet results;
synchronized (this.database) {
results = this.database.executeQuery(query);
if (results.next()) {
id = results.getInt(1);
query = "UPDATE Searches SET checked='1' WHERE ID_num='"
+ id + "'";
this.database.counter++;
System.out.println(this.database.counter);
System.out.println(id);
}
}
}
Core.java
for (int i = 0; i < verifier.length; i++) {
MySQL database=new MySQL();
verifier[i]=new Thread(new Verifier(database,i+1));
verifier[i].start();
}
MySQL.java
public class MySQL{
int counter=0;
....
}