In the class below, is the method getIt() thread safe and why?
public class X {
private long myVar;
public void setIt(long var){
myVar = var;
}
public long getIt() {
return myVar;
}
}
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.
It is not thread-safe. Variables of type
longanddoublein Java are treated as two separate 32-bit variables. One thread could be writing and have written half the value when another thread reads both halves. In this situation, the reader would see a value that was never supposed to exist.To make this thread-safe you can either declare
myVarasvolatile(Java 1.5 or later) or make bothsetItandgetItsynchronized.Note that even if
myVarwas a 32-bitintyou could still run into threading issues where one thread could be reading an out of date value that another thread has changed. This could occur because the value has been cached by the CPU. To resolve this, you again need to declaremyVarasvolatile(Java 1.5 or later) or make bothsetItandgetItsynchronized.It’s also worth noting that if you are using the result of
getItin a subsequentsetItcall, e.g.x.setIt(x.getIt() * 2), then you probably want tosynchronizeacross both calls:Without the extra synchronization, another thread could change the value in between the
getItandsetItcalls causing the other thread’s value to be lost.