Reputation: 467
I have 2 threads.
The first one calls this function
public int doCompute1(obj)
{
if (obj.state == OK_FOR_COMPUTE1)
{
// do something
obj.state = OK_FOR_COMPUTE2;
}
}
The second thread calls this function
public int doCompute2(obj)
{
if (obj.state == OK_FOR_COMPUTE2)
{
// do something
obj.state = OK_FOR_COMPUTE1;
}
}
For the moment it seems to work perfectly !
My question is: Is it correct ? Is it possible that on multicore processor, obj.state is in cache memory and then modifiyng this vaue by a thread, wouldn't be visible by the second thread?
What should I do if this code is not correct?
Upvotes: 0
Views: 113
Reputation: 2571
synchronized(obj){
if (...){
}
}
will do the stuff
EDIT:
What synchronized do?
synchronized(obj){ //if obj is not locked,i lock it and go to the if instruction.if obj is locked, i'm waiting for its unlocking
//some stuff that will run with no thread-interruption caused by other synchronized block locked on the obj object
}//the obj object is unlocked and let other methods enter their synchronized(obj) block
Upvotes: 2