Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing a method to lock its parent Object in Java

Is there a way in Java to get a method to lock (mutex) the object which it is in?

I know this sounds confusing but basically I wan't an equivelent to this snippet of C# but in Java.

lock(this)
{
    // Some code here...
}

I've been tasked with reimplementing an API written in .Net into Java, and I've been asked to keep the Java version as similar to the .Net version as humanly possible. This isn't helped by the fact that the .Net version looked like it was transcribed from a C++ version which I don't have access to.

Anyway the above line appears in the C# version and I need something that does the same in Java.

like image 323
Omar Kooheji Avatar asked Nov 30 '22 20:11

Omar Kooheji


1 Answers

The equivalent of that is:

synchronized (this)
{
}

(And no, you shouldn't generally do it in either C# or Java. Prefer locking on private references which nothing else has access to. You may be aware of that already, of course - but I didn't want to leave an answer without the warning :)

like image 130
Jon Skeet Avatar answered Dec 09 '22 20:12

Jon Skeet