Hashed Wheel Timer
Simple Hashed Wheel Timer implementation based on Agrona WheelTimer.
What is it?
Hashed Wheel Timer is an approximate timer with configurable accuracy, which could be used for very efficient single-threaded execution of scheduled tasks.
This implementation assumes single-writer principle and timers firing on processing thread.
Low (or NO) garbage.
Could be used with JDK6.
How to get?
<dependency>
<groupId>com.spikhalskiy</groupId>
<artifactId>hashed-wheel-timer</artifactId>
<version>0.2.0</version>
</dependency>
How to use?
final HashedWheelTimer wheel = new HashedWheelTimer(new SystemNanoClock(), 50, TimeUnit.MILLISECONDS, 512);
ScheduledExecutorService scheduledThreadPoolExecutor = Executors.newSingleThreadScheduledExecutor();
scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
wheel.expireTimers();
}
, 50, 50, TimeUnit.MILLISECONDS);
wheel.newTimeout(100, TimeUnit.MILLISECONDS, new Task() {
@Override
public void run(Timer timer) {
...
}
});
Implementation details
Based on Agrona's Wheel Timer, which is based on George Varghese and Tony Lauck's paper,
'Hashed and Hierarchical Timing Wheels: data structures to efficiently implement a timer facility'.
More comprehensive slides are located here.
Wheel is backed by arrays. Timer cancellation is O(1). Timer scheduling might be slightly
longer if a lot of timers are in the same tick. The underlying tick contains an array. That
array grows when needed, but does not currently shrink.
Timer doesn't create any threads inside. All processing and tasks executing perform in the calling thread.
Timer objects may be reused if desired, but all reuse must be done with timer cancellation,
expiration, and timeouts in consideration.