1

As I understand it, if there are only messages with a timestamp for the future in a MessageQueue, the MessageQueue blocks the Looper's loop until that time arrived. But this mechanism also works if the MessageQueue is completely empty and waiting for new input. How does the thread know how long to sleep / when to wake up in this case?

Florian Walther
  • 6,237
  • 5
  • 46
  • 104

1 Answers1

1

Threads have a "wait-notify" mechanism. When the thread is waiting, it's effectively sleeping. Once it's notified, it awakens and gets back to work.

Implementations of BlockingQueue make the polling threads wait if there are no items to serve, and notify all the sleeping threads when a new item is inserted. These threads then awaken and can take the newly inserted item.

More info about this mechanism can be found here (or by googling).

Vasiliy
  • 16,221
  • 11
  • 71
  • 127
  • Thank you. I tried to follow the source code but it ends at a native method that I couldn't find. But it is correct that the MessageQueue blocks if it is empty and the Looper doesn't just loop through its for-loop like crazy? – Florian Walther Mar 23 '19 at 22:01