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.
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.
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