5

I'm reading operating system and I came across several problems for inter-process communication. These can be solved by using monitor concepts which java provide via synchronized keyword.

I wish to know how synchronized keyword have been implemented? I tried to look at the source but I couldn't able to find it. Are synchronized are using system calls like down up ( which semaphore uses basically) to monitor the locks?

Does JVM help in this process?

I'm a novice in Java, I wish to know how things works before I go into thread concepts in java.

Thanks in advance.

sriram
  • 8,562
  • 19
  • 63
  • 82
  • See also http://stackoverflow.com/questions/1898374/does-the-jvm-create-a-mutex-for-every-object-in-order-to-implement-the-synchron – Raedwald Oct 08 '13 at 13:44
  • possible duplicate of [How does JVM make sure only one thread can acquire the lock of an object?](http://stackoverflow.com/questions/28344338/how-does-jvm-make-sure-only-one-thread-can-acquire-the-lock-of-an-object) – Raedwald Feb 05 '15 at 23:44

1 Answers1

6

How synchronized is implemented is not defined, only how it works.

In many JVMs, what it does is quite complicated to optimise its behaviour (for example it tries to avoid making system calls as these are relatively slow) For example the JIT can combine or eliminate locking with the synchronized keyword if it determines this can be done.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • You mean without the system call's help, Java would have implemented this feature? – sriram Sep 11 '12 at 07:59
  • The JIT generates native code which implements this feature. It typically spin locks for a time and makes a system time as a fall back. It doesn't call existing code as such. – Peter Lawrey Sep 11 '12 at 08:00
  • @PeterLawrey Is implementation of "synchronized" within the scope of JVM (other than JIT optimization you mentioned) or it is an issue of OS? Either way, I would like to understand at least some abstract implementation details at JVM/OS/Hardware level to know how is CAS better than "synchronized" ? – user104309 Jun 28 '18 at 16:12
  • @user104309 a CAS is always more light weight unless you have Hardware Transaction Memory support, but this is in part due to CAS being much more limited in what is does. I would start with `synchronized` first and consider CAS if you profile a performance issue. – Peter Lawrey Jun 29 '18 at 08:27