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;
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
bis notvolatilethe JIT can and will optimiseto be
so the value of
bis not read each time.