if I have a getter method that has only one statement like this
public class NumberClass{
int number;
public int getNumber() {
return number;
}
...
}
and multiple threads access this method, do I have to synchronize this method or it is not necessary since it has only one statement??
It has nothing to do with 1 or more statements. It depends on whether or not the value has been updated in another thread and if you want all of the threads to see a consistent value.
If the
numberfield was updated in thread1, then thread2 may get either the original value or the new value depending on how the update was synchronized. To have the value published appropriately both the set and get methods need tosynchronized.If you are just trying to share an
intvalue then marking thenumberfield as beingvolatilewould work or using anAtomicIntegerto share the value between multiple threads reliably may be more appropriate.or use: