James L
James L

Reputation: 16854

Should my field be volatile when initializing on a background thread?

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

Answers (1)

Henk Holterman
Henk Holterman

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

Related Questions