JDK delay queue
PriorityQueue
DelayQueue implementation in JDK
Internal structure: DelayQueue is a specialized PriorityQueue that orders elements based on their delay time.
Characteristics: When the consumer wants to take an element from the queue, they can take it only when the delay for that particular element has expired.
Pros:
Not introduce other dependencies
Cons:
It is only a data structure implementation and all queue elements will be stored within JVM memory. It would require large amounts of efforts to build a scalable delay queue implementation on top of it.
DelayedQueue interface
Algorithm: When the consumer tries to take an element from the queue, the DelayQueue will execute getDelay() to find out if that element is allowed to be returned from the queue. If the getDelay() method will return zero or a negative number, it means that it could be retrieved from the queue.
Data structure:
Test with Producer/Consumer pattern
Reference
Timer mechanism (Signaling)
Busy waiting
Def: Setting the signal values in some shared object variable. Thread A may set the boolean member variable hasDataToProcess to true from inside a synchronized block, and thread B may read the hasDataToProcess member variable, also inside a synchronized block.
Example: Thread B is constantly checking signal from thread A which causes hasDataToProcess() to return true on a loop. This is called busy waiting
Wait notify
Pros:
Reduce the CPU load caused by waiting thread in busy waiting mode.
Cons:
Missed signals: if you call notify() before wait() it is lost.
it can be sometimes unclear if notify() and wait() are called on the same object.
There is nothing in wait/notify which requires a state change, yet this is required in most cases.
Spurious wakeups: wait() can return spuriously
Reference
Single machine delayed scheduler
https://soulmachine.gitbooks.io/system-design/content/cn/task-scheduler.html
https://zhuanlan.zhihu.com/p/228420432
Naive impl in Java: https://medium.com/nerd-for-tech/distributed-task-scheduler-redis-329475df9dcf
Last updated