In C# it\'s pretty straightforward:
class Class1{
private static readonly object locker = new object();
void Method1(){
lock(locker) { .... }
}
}
If the premise is that you want to avoid locking on this
because another thread with third party code can lock on the same object, then Scala offers one more level of visibility private[this]
.
class C {
private[this] val lock = new Object()
def method1(): Unit = lock.synchronized {
println("method1")
}
}
Here actually no other object other than a particular instance of C
can access lock
. Even other instances from the same class cannot access lock
.