Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my class threadsafe? If not why?

Tags:

java

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;
 }
}
like image 687
auser Avatar asked Oct 01 '12 14:10

auser


People also ask

Is a class thread-safe?

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.

How do you know if a class is thread-safe?

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.

Are class variables 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.

What does it mean to say that a class is thread-safe?

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.


2 Answers

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.

like image 100
Peter Lawrey Avatar answered Oct 14 '22 02:10

Peter Lawrey


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.

like image 7
kosa Avatar answered Oct 14 '22 04:10

kosa