1

A Java thread A fails to execute synchronized statement as another thread has got the monitor.
The thread A is queued by the JVM?
And how thread A is activated after, via 1) or 2) ?

  1. As soon as the monitor is released JVM will send up this signal , thread A may be activated
  2. the JVM will detect whether the monitor is available in a period of time, if the monitor is available, thread A may be activated
Hooman.AS
  • 190
  • 1
  • 3
  • 18
user2351281
  • 137
  • 1
  • 8
  • What happens: the thread is blocked, and will stop and not proceed. It's a bit like queueing but depends on the OS and the thread library used.. #2 is closest; when a thread is unblocked, it's put in the ready queue (ready = able to run) but may not run immediately if the OS has other threads/processes that are running and still able to proceed. – markspace Dec 15 '18 at 03:47
  • One addendum: last I checked, the JVM could optimize a synchronized block that seldom was contested (seldom blocked) and turn the synchronized check into a spin-lock. These don't queue, they just burn CPU cycles until the lock is released. – markspace Dec 15 '18 at 03:51
  • _"fails to execute"_ You may want to qualify what you mean with 'failed', because it doesn't fail, it just waits until it can proceed. – Mark Rotteveel Dec 15 '18 at 09:08
  • yes,perfect answer @markspace I mainly am confused whether the blocked thread which is because of 'synchronized' sentence is informed by the monior release action like the blocked thread which is because of 'wait' sentence is informed by `notify` sentence – user2351281 Dec 19 '18 at 08:47
  • What I mean for 'fails to execute' is it is blocked until can obtain the monitor @MarkRotteveel – user2351281 Dec 19 '18 at 08:52
  • So your question is actually about `notify`? `notify` wakes up **one** thread. It may or may not be thread A if there is more than one thread blocked. It is also possible to "miss" the notification if thread A hasn't actually blocked when the `notify` is invoked. Since your question got closed you might want to ask again, with more emphasis on the `notify` if that's what you're interested in. – markspace Dec 19 '18 at 17:31

1 Answers1

1

The Java Language Specification says it in section 17.1 Sysnchronization:

[...] Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. [...]

Lolo
  • 4,277
  • 2
  • 25
  • 24