user961690
user961690

Reputation: 778

object synchronization

When a synchronized block is used for synchronization on an object instance, then threads compete to get into object's implicit monitor. And once, any particular thread enters into the monitor, any other thread has to wait for entering into it. Then

synchronized(object){
  // some code here
  // no function call
}

must not enforce taking any particular type of object. Thus any object type can be used here because every object has its implicit monitor.

Kindly reply me is it true?

Upvotes: 8

Views: 4214

Answers (2)

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

Yes, every Java Object can act as a monitor.

And since this is such a short answer, for bonus, this is an interesting read: Does the JVM create a mutex for every object in order to implement the 'synchronized' keyword? If not, how?

Also note that C# does something similar with their objects, but also have value types (which are not Monitors)

Upvotes: 10

Gabe
Gabe

Reputation: 86768

Just keep in mind that if you have a variable that is null, you cannot lock it. Also, while things like Integer are objects, an int or float is not. You can lock an Integer or int[], but not an int.

Upvotes: 6

Related Questions