• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization primitives

 
Ajay Saxena
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the underlying synchronization primitive implementation of the keyword synchronized in Java?

How does the JVM actually translate it into low level synch primitives?
 
Henry Wong
author
Sheriff
Posts: 22516
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All modern processors have an machine op code -- called the CAS operator. On some machines, it means Compare-N-Set, on others it means Compare-N-Swap. Regardless, it is an atomic operation, that is guaranteed to work across the processors cores on the computer.

This instruction is used as the basic building block for synchronization. With this op code, it is possible to atomically grab a lock, if it is free -- across all the processors.

Henry
 
Carey Evans
Ranch Hand
Posts: 225
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And there�s more information on the HotSpot Internals wiki, under Synchronization.

You can get access to the CAS operation from Java using AtomicBoolean, AtomicInteger, etc.
 
Henry Wong
author
Sheriff
Posts: 22516
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can get access to the CAS operation from Java using AtomicBoolean, AtomicInteger, etc.


Yea. The Java designers realized that they made a big mistake by hiding the CAS operator. Synchronization is great, but it doesn't allow for optimistic locking.

So, with Java 5, they fixed it with the Atomic variables.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!