Domanda

this is my first question ever so please be gentle on me.

What happens when two threads, say t1 and t2, running on separate CPU cores invoke a synchronized method on a shared object AT THE SAME TIME, i.e. in the same nanosecond/processor cycle? How and by what element of the architecture is the lock resolved?

It may seem like an obvious question but i could not find anything on the internet. Thanks!

È stato utile?

Soluzione 2

The spec simply says the synchronized method may only be entered by one thread at a time. What architecture mechanism is used would depend on the JVM.

In the case of Oracle HotSpot (the JVM that almost everyone runs): the C++ code is GNU, and probably holds the answer for you.

But if you just need the assurance that it "just works", the specification gives that to you.

Altri suggerimenti

These days this is actually realized in hardware, so the processor has a special instruction to grant one thread out of many access. This has evolved from a pure software-based solution from last century, and the state of the art these days is what the AtomicInteger represents: a single, mutable integer, that is guaranteed to be thread-safe but never blocks.

Example: The Intel Haswell Architecture.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top