JavaDeveloper
JavaDeveloper

Reputation: 5660

Synchronization under covers

I was trying to dive into synchronization.

here, its mentioned "Every object has an intrinsic lock associated with it.".

  1. I understand Object class. Its ( quite known to us ) does not have any property like a lock ( thus i guess its called intrinsic lock ). What exactly is this lock (ie is it a Lock.java class ? it is some sort of hidden field ? ) and how is it associated with an object (ie is there some mystery implicit reference to the lock from an object, something happening natively ) ?

  2. When several threads try to acquire the same lock, one or more threads will be suspended and they will be resumed later. Well where are these threads stored ? What data structure keeps records of waiting threads ?

  3. What logic is used under the covers to pick a thread waiting to enter synchronized method, when there are many waiting ?

  4. Any reference to what happens under the covers (step by step) from "synchronized keyword" to "intrinsic lock aquisition" ?

  5. Is there an upper limit on number of threads that are allowed to wait on synchronized ?

Upvotes: 0

Views: 27

Answers (1)

keshlam
keshlam

Reputation: 8058

1) Yes, the lock is essentially a hidden field on the object. You can't access it except through synchronization.

2) Waiting threads essentially just sleep until the lock is available. They aren't "stored" anyplace special, nor is there a visible queue of waiting threads. Details of implementation are hidden.

3) I don't think there's any promised order. If you explicitly need round-robin scheduling or prioritization or something of that sort, it's your responsibility to implement it (or use a class which implements it for you) on top of the synchronization lock mechanism.

4) This is likely to be handled as an OS semaphore, if you understand those. If you don't, defining them strikes me as too much detail to be addressed properly here... and you don't really need to understand this unless you're reimplementing it.

5) There is no explicit limit, as far as I know. (I haven't checked the official Java Specification, but I understand how this kind of thing gets implemented at the OS level.) Of course at some point you're going to run out of system resources, but I think you'll generally run out of other resources (like memory to run those threads in) first.

One additional note: It's also worth looking at the Atomic... classes. When these can be used, they will be somewhat more efficient in modern processors than traditional Java synchronization can be.

Upvotes: 2

Related Questions