-1

I know only one thread will get the monitor lock. But what happens to all the other wait() ing threads at the low level ? ( Since they are all notified ) Will they all wake up and enter some kind of expensive spin lock ? Or will they go back to being blocked on teh lock again ? Looking for the low level details - particularly trying to see if CPU will be consumed as a result of this ?

Also when a thread is waiting on a monitor, is the actual OS thread taken away from it behind the scenes ? ( So that the OS thread can be used to do useful work )

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Sony Antony
  • 314
  • 1
  • 11
  • What does the javadoc say happens? – Sotirios Delimanolis Nov 17 '15 at 15:27
  • as the name says: `notifyAll()` will notify (wake up) all threads that have waited (with `wait()`) on a specific object! All threads execute the next line after the `wait()` – ParkerHalo Nov 17 '15 at 15:28
  • I'd say that if any of these mattered in your use case (performance wise), you would know the details. The documentation recommends using `notifyAll()`, so I suggest you go with that and stop worrying about your CPU. – Kayaman Nov 17 '15 at 15:29

1 Answers1

1

The answers to the linked question don't address these points specifically.

The threads that are notified with notifyAll get woken up, then they try to acquire the lock they were blocked waiting on (along with any newly-arrived threads that want to acquire the lock). The scheduler picks a winner, and the losers go back to blocking again.

The OS thread does not get reassigned away from the Java thread object, the OS-level thread blocks. You can confirm this by watching the threads in a performance monitoring tool. Scheduling and blocking are all occurring at the OS level (except for green threads, where threads are simulated by the JVM).

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • [ Thanks. ( Yes the linked question does not answer my question at all - I had already googled for an answer before I posted this ). ] – Sony Antony Nov 17 '15 at 16:38