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??
I have to synchronize this [get] 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 number field 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 to synchronized.
If you are just trying to share an int value then marking the number field as being volatile would work or using an AtomicInteger to share the value between multiple threads reliably may be more appropriate.
private volatile int number;
or use:
private AtomicInteger number = new AtomicInteger();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With