I have a requirement that should assign a counter variable for each thread that gets invoked. But I am not getting the expected results, actually the counter is duplicating in the threads. I created a dummy table and a proc to insert the counter value into the table. Is there anyway that the code can be changed so that the thread gets an incremented value.
In the below code, the variable counter is a static int
public synchronized int testSequence(){
System.out.println("testSequence::::: "+counter++);
//Random rn = new Random();
CallableStatement cstmt;
{
try {
cstmt = conn.prepareCall("{call insertjtest(?)}");
cstmt.setInt(1,counter);
//cstmt.setInt(1, rn.nextInt());
cstmt.execute();
cstmt.close();
conn.commit();
return counter;
} catch (SQLException e) {
// TODO Auto-generated catch block
return 0;
}
}
}
But I find the
if you want :
EDIT :
After having seen your code, it is one counter for all threads, so you can use an AtomicInteger for all and it is not necessary to be synchronized because AtomicInteger is a multithreaded object.