Reputation: 16854
On application startup, I am instantiating a class on a background thread, then assigning it to a variable. I later access that variable from my main thread. This variable is only assigned once.
My understanding is that I don't need to use the volatile keyword here, because the reference could not be cached until it is first accessed in the UI thread. Am I correct in my thinking, or am I missing something?
Upvotes: 4
Views: 93
Reputation: 273169
Am I correct?
Yes. Caching is only an issue when one thread repeatedly reads a variable (written to from another thread).
And because assigning to a reference is atomic you're safe.
Upvotes: 3