Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized keyword internal implementation

How does JVM make sure threads acquire a lock after entering synchronized method of an object?

like image 968
Arijeet Saha Avatar asked Sep 20 '14 13:09

Arijeet Saha


1 Answers

Broad question:

How does the JVM make sure...?

The "VM" in "JVM" stands for "virtual machine." Your code doesn't do anything by itself. When we say, "your code runs", what we really mean is, the JVM executes your instructions. And it does so in accordance with the rules that are laid out in the JVM specification. One of the rules says that a JVM must never execute a synchronized block for two different threads on the same object at the same time.

But there are many layers to the onion: A typical JVM uses native threads (i.e., threads provided by the operating system) to implement Java threads, and it typically relies on mutex objects provided by the OS to synchronize the threads.

Going deeper still, neither the JVM nor the operating system really does anything by itself: It's the computer hardware executing the instructions of the OS and the JVM that really makes things happen.

The complete answer to "how does synchronization work?" is a couple of chapters from a book about operating system design, plus a couple of chapters from a book on computer architecture, plus a shot of computer science on the side. To fully understand it all, you'll at least need to know about:

  • "user-mode instructions" vs. "privileged mode instructions",
  • How system calls work,
  • How an operating system "scheduler" performs "Context Switches"
  • hardware synchronization primitives like "Compare and Swap (CAS)", "Test and Set (TAS)", "load-link/store-conditional (LL/SC)"

They're all subjects that you can look up on Wikipedia, but IMO, books are better for learning a subject of that depth.

like image 140
Solomon Slow Avatar answered Sep 21 '22 06:09

Solomon Slow