Answer by Stephen C for Are java getters thread-safe?
The short answer is your example will be thread-safe, if the variable is declared as volatile, orthe getter is declared as synchronized.The reason that your example class A is not thread-safe is that...
View ArticleAnswer by Brett Okken for Are java getters thread-safe?
Your best solution is to use an AtomicInteger, they were basically designed for exactly this use case.If this is more of a theoretical "could this be done question", I think something like the...
View ArticleAnswer by gexicide for Are java getters thread-safe?
You basically have two options:1) Make your int volatile2) Use an atomic type like AtomicIntusing a normal int without synchronization is not thread safe at all.
View ArticleAnswer by Gray for Are java getters thread-safe?
Is is okay to synchronize all methods which mutate the state of an object, but not synchronize anything which is atomic? In this case, just returning a field?Depends on the particulars. It is important...
View ArticleAnswer by NESPowerGlove for Are java getters thread-safe?
It's not thread safe because that getter does not ensure that a thread will see the latest value, as the value may be stale. Having the getter be synchronized ensures that any thread calling the getter...
View ArticleAre java getters thread-safe?
Is is okay to synchronize all methods which mutate the state of an object, but not synchronize anything which is atomic? In this case, just returning a field?Consider:public class A{ private int a = 5;...
View Article