This week's giveaway is in the Threads forum.
We're giving away four copies of Java Concurrency Live Lessons and have Doug Schmidt on-line!
See this thread for details.
Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization primitives  RSS feed

 
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: 22866
119
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: 22866
119
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!