Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Singleton Object with Multi-threading

Using play, my Controller calls the Foo service, an object. This object, which uses val's and immutable data structures only, will be called by multiple clients.

When my Controller calls Foo.doQuery() in multiple threads, what will happen?

If client 1 makes a call that performs Foo.doQuery(), will client 2's call to Foo.doQuery() have to wait?

I'm curious if I should simply create a new class per instance of Foo, but I'd like to know what happens with a Scala singleton, using val's only, in a multi-threaded environment.

like image 803
Kevin Meredith Avatar asked Nov 12 '13 16:11

Kevin Meredith


1 Answers

No, a Scala object doesn't imply a lock ('synchronized' in java), so the client 2 doesn't have to wait. Both client 1, client 2 and client n can run concurrently if you don't explicitly add locks to the code.

Think of

object MyObject { ... }

as

class MyClass(..) { ... }
lazy val MyObject = new MyClass(..)

A lock can be applied with the 'synchronized' function like this:

def doQuery = synchronized {
  ..
  ..
}

== EDIT ==

As for your question in the comment, the thread (or call) stack and variable sharing have nothing to do with your controller using immutable references and/or immutable data structures. What matters is where you define your variables. If you define a variable, be it a val or var, inside a method (method variable), then every time the method is called, that variable is created just for the calling thread. On the other hand, if you define your variable at the class or object level (instance variable), all calls to the instance method always share the same instance variable.

In your case, I think you can implement your controller as a singleton object since immutable references and data structures are well.. immutable. It doesn't matter if they're shared or not.

like image 87
harp seal pup Avatar answered Sep 24 '22 02:09

harp seal pup