I have a function that launches a couple of threads (it’s a test function) and one of the threads mutates the state of a variable. Since local variables cannot be marked volatile, I would assume that multiple threads in that method will always have the updated state of the variable. Is this correct? Here is the sample code
public void someMethod() {
MutableBoolean mb = new MutableBoolean(false);
Thread t1 = new Thread() {
public void run() {
while (someCondition) {
if ( mb.getValue() ) {
...do something
}
}
}
}
t1.start();
Thread t2 = new Thread() {
public void run() {
if ( someCondition ) {
mb.setValue(true);
}
}
}
t2.start();
...wait for the threads to complete
}
Unless MutableBoolean uses a lock in it’s set/get value methods, or it’s an atomic operation then this isn’t threadsafe.
getValue could be reading the value while setValue is updating it. You might get away with this with a boolean, but for any more complex type it’ll probably fail.
Put a lock around the access to shared state to make it thread safe.