I found this question in one of the forums so thought of sharing it
public class X {
private long myVar;
public void setIt(long var){
myVar = var;
}
public long getIt() {
return myVar;
}
}
We all know that it is not thread safe as its possible that two concurrent threads may try to update and access the myVar at the same time. But an alternate answer i found was this
"It's not thread-safe because the instance variable is a 64-bit primitive. Read-only operations on instance-level primitives are atomic for 32-bit variables. But atomicity is not guaranteed for 64-bit variables because the JVM spec allows implementations to use two 32-bit read operations to access a 64-bit value. If a thread is in the process of reading the two 32-bit words of myVar, an interrupting thread could write to the high or low word of myVar before the first thread successfully reads both. This would result in a corrupt return value from getIt()."
No comments:
Post a Comment