Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a scala object, is an immutable val thread safe?

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?

like image 636
sam Avatar asked Oct 11 '17 02:10

sam


People also ask

Is immutable object thread-safe?

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.

Can we use immutable objects in multithreading?

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.

Is Scala mutable HashMap thread-safe?

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.

Is Scala list thread-safe?

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.


1 Answers

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.

like image 91
Artavazd Balayan Avatar answered Sep 29 '22 04:09

Artavazd Balayan