object Users {
val userCountByAgeMap = readFromFile(); // read from file returns immutable map
}
As in above example in scala, Users will be Singleton object and userCountByAgeMap will be initialized lazily.
So is this initialization atomic? i.e. one and only one thread will be able to initialize it.
Suppose userCountByAgeMap is initialized by Thread A, will it be visible to Thread B.
If initialization is not atomic/memory visibility not ensured, will making userCountByAgeMap variable as lazy val fix it?
An immutable object is one whose state can't be changed once the object is created. Immutable objects are, by their very nature, thread-safe simply because threads have to be able to write to an object's instance variables to experience a read/write or write/write conflict.
Immutable objects are useful in multithreaded applications because they can be safely accessed by several threads concurrently, without the need for locking or other synchronization.
The HashMap in the Scala standard library is not thread-safe. This means that if multiple fibers are accessing the same key, and trying to modify the value, this can lead to inconsistent results.
Note: Despite being an immutable collection, the implementation uses mutable state internally during construction. These state changes are invisible in single-threaded code but can lead to race conditions in some multi-threaded scenarios.
In Scala, an object is initialized in a static block so thread safety is guaranteed by JVM (Java static initializers are thread safe). You can use JAD decompiler to analyzer bytecode. Here is the code:
object Users {
val userCountByAgeMap = Map.empty[String, Int]
}
And decompiled Users$.class file:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Users.scala
import scala.Predef$;
import scala.collection.immutable.Map;
import scala.collection.immutable.Map$;
public final class Users$
{
public Map userCountByAgeMap()
{
return userCountByAgeMap;
}
private Users$()
{
userCountByAgeMap = Predef$.MODULE$.Map().empty();
}
public static final Users$ MODULE$ = this;
private final Map userCountByAgeMap;
static
{
new Users$();
}
}
As you're using immutable Map which automatically gives you thread safety. So it's ok to access this field from different threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With