java threads synchronization
java, multithreading, synchronization
Solution
It is not thread-safe. Variables of type `long` and `double` in 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 `myVar` as `volatile` (Java 1.5 or later) or make both `setIt` and `getIt` `synchronized`.
Note that even if `myVar` was a 32-bit `int` you 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 declare `myVar` as `volatile` (Java 1.5 or later) or make both `setIt` and `getIt` `synchronized`.
It's also worth noting that if you are using the result of `getIt` in a subsequent `setIt` call, e.g. `x.setIt(x.getIt() * 2)`, then you probably want to `synchronize` across both calls:
synchronized(x)
{
x.setIt(x.getIt() * 2);
}
Without the extra synchronization, another thread could change the value in between the `getIt` and `setIt` calls causing the other thread's value to be lost.
Problem
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; } } ```