I am trying to synchronize a int counter between few threads (6). Below is my worker class. I am trying to synchronize my private field countertest
:
public class DbWorker implements Callable {
private final Object lock = new Object();
private int countertest = 0 ;
private boolean IsActive(Integer act)
{
synchronized(lock){
boolean exists = false;
countertest++;
....
System.out.println("countertest IS : " + countertest );
}
return true;
}
public void run() {
....
IsActive(act):
...
}
}
In my main class I am creating threads using for loop and ExecutorService. Please see below:
private ExecutorCompletionService<Integer> _objQueue ;
for(int j = 0; j < 6; j++){
_objQueue.submit( new DbWorker( "SOME PARAMETER" , _snapshots.get(j) , j ) );
}
My countertest variable is not synced it is printing different number (non-sequential). What am I doing wrong?