Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...