Is my class threadsafe? If not why?
class Foo {
boolean b = false;
void doSomething() throws Exception {
while (b) Thread.sleep();
}
void setB(boolean b) {
this.b = b;
}
}
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The HashMap is a non-synchronized collection class.
For a standard Java SE class, the best way to know whether or not the class is thread-safe is to carefully read its documentation. Always read both the class documentation and the method documentation. If either say it's not synchronized or not thread-safe, you know it's not thread-safe.
Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
The code is not thread safe because a running thread may see changes until the code is compiled (which could be at a random point later) and you no longer see changes.
BTW: This makes testing it very hard to do. e.g. if you sleep for 1 second you might not see this behaviour for almost three hours.
i.e. it may or may not work and you cannot say just because it has worked it will continue to work.
As b
is not volatile
the JIT can and will optimise
while (b) Thread.sleep(N);
to be
boolean b = this.b;
if (b) while (true) Thread.sleep(N);
so the value of b
is not read each time.
It is not. setB()
updating instance variable b
value but is not synchronized
.
Multiple threads may try to execute setB()
method at same point of time may result in un-predicted results.
You need to synchronize
the method (or) use synchronize
block with lock on this
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With