Johnny
Johnny

Reputation: 21

How to have a thread safe data in scala

Newbie in Scala here.

I'm doing a simple project in Scala with a simple web service, so I don't want to use a full blown db.

All my application is immutable. But I don't know how to do the "data" part.

My web service has GET and some POST and PUT. So I'd like my data to be: - stored in memory - thread safe (so many concurrent PUT won't mess it - immmutable? (I'm new to the concept, but I guess is not possible)

I thought of an object like:

object UserContainer {
    var users: List[User] = initializeUsers()

    def editUser(...) = ...
    def addUser(...) = ...
}

But it's not thread safe, neither immutable. I found that I can use "Actors" or "synchronize" for this. How should I approach?

Upvotes: 1

Views: 255

Answers (1)

Soumya Simanta
Soumya Simanta

Reputation: 11741

The primary concurrency abstraction provided by Actors is to provide threadsafe access to mutable state in a asynchronous and non-blocking fashion. Looks like that is your use case.

Some options for building build web services you should look at Spray.io or akka-http - both of which are based on Akka actors. However, creating actors (esp. using Akka) needs an ActorSystem which some argue is heavyweight. Additionally, actors (as of today) are not typed, so you don't get the type safety of Scala.

Upvotes: 2

Related Questions