How to create a synchronized object method in scala
Asked Answered
C

1

9

Does scala support synchronized object (/static) methods? I am looking for:

synchronized def myObjectMethod(): <SomeReturnType> = {
.. 
 }

If this were not supported, what is the equivalent in scala ?

Crowther answered 6/3, 2015 at 3:41 Comment(0)
I
28

synchronized in scala is just a method1. So you can do

def myObjectMethod: SomeReturnType = synchronized {
  // stuff
}

It's actually a special method injected by the compiler, more details here: How is the synchronized method on AnyRef implemented?

Intrigante answered 6/3, 2015 at 3:47 Comment(2)
I have a method with Try {} , how can use synchronuzed ?Palpitant
Doesn't synchronized synchronize with this? So if I have def foo = synchronized{ /* stuff */}; def bar = synchronized{ /* other stuff */ }, will I be able to run the two concurrently (i.e., foo and bar can run at same time but one at most copy of each)Healy

© 2022 - 2024 — McMap. All rights reserved.