8

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?

home
  • 12,468
  • 5
  • 46
  • 54
user961690
  • 698
  • 1
  • 11
  • 22
  • 6
    So polite and well-mannered! – Josh Pordon Sep 23 '11 at 18:05
  • @Josh: quite the opposite, actually - using the term "respected programmers" implies that some of us *aren't* (which assertion is true, of course). – MusiGenesis Sep 23 '11 at 18:12
  • 3
    Everyone who is sensible enough to understand that I was greeting everyone needs to be greeted yet again. Thanks Pordon Sir, for noticing my respect for every one. And MusiGenesis, everyone who considers himself worthy of respect is respectable. Those who thought my respect was meant for them, were pleased and others............ – user961690 Sep 23 '11 at 18:39
  • 1
    Oh my God!! He is a Lord! I swear i think you are all lost!!! Where your race lives????? – Plínio Pantaleão Sep 26 '11 at 14:18

2 Answers2

10

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)

Community
  • 1
  • 1
Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
6

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.

Gabe
  • 84,912
  • 12
  • 139
  • 238