I'm wondering if the following class is thread safe:
class Example {
private Thing thing;
public setThing(Thing thing) {
this.thing = thing;
}
public use() {
thing.function();
}
}
Specifically, what happens if one thread calls setThing while another thread is in Thing::function via Example::use?
For example:
Example example = new Example();
example.setThing(new Thing());
createThread(example); // create first thread
createThread(example); // create second thread
//Thread1
while(1) {
example.use();
}
//Thread2
while(1) {
sleep(3600000); //yes, i know to use a scheduled thread executor
setThing(new Thing());
}
Specifically, I want to know, when setThing is called while use() is executing, will it continue with the old object successfully, or could updating the reference to the object somehow cause a problem.
Thing
is. – shmosel Nov 22 '17 at 0:28thing
will never be null in your example since variable assignments are atomic in Java (expect for long and double). However, thread1 may still use an older object of Thing after thread2 has set it to a new value. Declare thing asvolatile
to avoid this. thread1 will always complete the execution of thefunction()
method using the same Thing-Object – codeflush.dev Nov 22 '17 at 0:58