You are given a Timer class that has access to a single underlying system timer API that can only keep one active timer at a time.
Underlying single-timer primitives (already available)
class Timer {
// Schedule ONE timer to fire at `timestamp` (absolute time).
// If called again, it overrides/cancels the previously scheduled system timer.
private void setTimer(long timestamp);
// Called automatically when the currently scheduled system timer expires.
private void handleTimer();
// Returns current time as an absolute timestamp (same unit as setTimer).
private long getCurrentTime();
// Public API: users can call this to schedule MANY timers.
public void setNewTimer(long timestamp);
}
Requirements
-
Users can only call
setNewTimer(timestamp)
.
-
setNewTimer
must support
multiple
outstanding timers.
-
When any user timer expires,
handleTimer()
should be invoked (once per expired user timer).
-
You must implement the logic of the four methods so that multiple user timers are correctly managed on top of the single underlying
setTimer
.
Clarifications you may assume
-
timestamp
is an
absolute
time value (e.g., epoch milliseconds) comparable to
getCurrentTime()
.
-
Multiple user timers may share the same timestamp.
-
If a timer is set for a time ≤
getCurrentTime()
, it should fire “immediately” (as soon as the system can schedule it).
Discuss data structures, time/space complexity, and important edge cases (e.g., overrides, duplicate timestamps, and concurrency if relevant).