Reads and writes to references are always atomic in java, so, at least, you are not risking to crash your JVM by doing this.
However:
(1) What you write to that var in one thread other threads are not guaranteed to see until both writing and reading threads hit a memory barrier (which are not actually mentioned anywhere in the JLS, and are therefore implementation-specific). From a practical standpoint, I would say, it is sort of unusual to expect an active thread in a modern JVM application to not hit a memory barrier every few milliseconds or so, but still, it is not impossible for other threads to no see the value your thread has written for hours.
This is pretty easily fixable by adding @volatile
annotation to your var
- that ensures that the write is committed immediately, and every read that happens after that write will see the new value. But ...
(2) Seeing var
in scala code is bad enough for a reader in terms of cognitive load. The issue, also known as "code smell" is that someone, even moderately used to scala, who's reading this code is going to pause and waste cycles figuring out "why we need a var here?", and "is it going to cause problems"? I won't get into much more details on this, because mutability is not a topic here, just trust me that that is bad enough. But what you have is not just a var
, it's a var
, that is externally accessible, and concurrently modified by multiple threads.
Long story short, just give the reader of you code a break, and use AtomicReference
. It has literally no cost (compared to using @volatile
, which is a bit costly, but only a little, and I don't see how you can get around it anyway), just pure benefit.