Quantcast
Channel: Are java getters thread-safe? - Stack Overflow
Browsing latest articles
Browse All 6 View Live

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 Article



Answer 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 Article

Answer 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 Article

Answer 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 Article

Answer 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 Article


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?Consider:public class A{ private int a = 5;...

View Article
Browsing latest articles
Browse All 6 View Live


Latest Images