From 98d1fee994302f5e2ad7a7b60de2f2d74f35408b Mon Sep 17 00:00:00 2001 From: Alex Vakulenko Date: Mon, 1 Feb 2016 12:25:21 -0800 Subject: Periodicly clean up command queue and remove old processed commands Do periodic command queue cleanup to reclaim memory from commands that have been in terminal state for certain period of time (5 mins). Change-Id: Ief9cdbf023a222412c296644c9e927c4be000024 Reviewed-on: https://weave-review.googlesource.com/2434 Reviewed-by: Alex Vakulenko --- src/commands/command_queue.h | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) (limited to 'src/commands/command_queue.h') diff --git a/src/commands/command_queue.h b/src/commands/command_queue.h index 01839d8..a092c12 100644 --- a/src/commands/command_queue.h +++ b/src/commands/command_queue.h @@ -14,8 +14,10 @@ #include #include +#include #include #include +#include #include "src/commands/command_instance.h" @@ -23,7 +25,7 @@ namespace weave { class CommandQueue final { public: - CommandQueue() = default; + CommandQueue(provider::TaskRunner* task_runner, base::Clock* clock); // TODO: Remove AddCommandAddedCallback and AddCommandRemovedCallback. using CommandCallback = base::Callback; @@ -64,23 +66,29 @@ class CommandQueue final { // Removes a command identified by |id| from the queue. bool Remove(const std::string& id); - // Removes old commands selected with DelayedRemove. - void Cleanup(); + // Removes old commands scheduled by RemoveLater() to be deleted after + // |cutoff_time|. + void Cleanup(const base::Time& cutoff_time); - // Overrides CommandQueue::Now() for tests. - void SetNowForTest(base::Time now); + // Schedule a cleanup task to be run after the specified |delay|. + void ScheduleCleanup(base::TimeDelta delay); - // Returns current time. - base::Time Now() const; + // Perform removal of scheduled commands (by calling Cleanup()) and scheduling + // another cleanup task if the removal queue is still not empty. + void PerformScheduledCleanup(); - // Overridden value to be returned from Now(). - base::Time test_now_; + provider::TaskRunner* task_runner_{nullptr}; + base::Clock* clock_{nullptr}; // ID-to-CommandInstance map. std::map> map_; - // Queue of commands to be removed. - std::queue> remove_queue_; + // Queue of commands to be removed, keeps them sorted by the timestamp + // (earliest first). This is done to tolerate system clock changes. + template + using InversePriorityQueue = + std::priority_queue, std::greater>; + InversePriorityQueue> remove_queue_; using CallbackList = std::vector; CallbackList on_command_added_; @@ -88,6 +96,9 @@ class CommandQueue final { std::map command_callbacks_; Device::CommandHandlerCallback default_command_callback_; + // WeakPtr factory for controlling the lifetime of command queue cleanup + // tasks. + base::WeakPtrFactory weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CommandQueue); }; -- cgit v1.2.3