Sepia::MemoryLimiter
Memory pressure detection and management system.
Monitors system memory usage and provides signals for when caches should be purged or memory-saving measures should be taken. Works across different platforms (Linux, macOS, Windows).
Example
limiter = MemoryLimiter.new(
warning_threshold: "70%",
critical_threshold: "85%",
check_interval: 30.seconds
)
limiter.on_warning { puts "Memory usage is high" }
limiter.on_critical { cache.clear }
limiter.start_monitoring
Constructors
Creates a new memory limiter.
Parameters
- warning_threshold : Memory usage percentage for warning (default: 0.7 = 70%)
- critical_threshold : Memory usage percentage for critical (default: 0.85 = 85%)
- emergency_threshold : Memory usage percentage for emergency (default: 0.95 = 95%)
- check_interval : How often to check memory usage (default: 30 seconds)
Example
limiter = MemoryLimiter.new(
warning_threshold: 0.75,
critical_threshold: 0.90,
check_interval: 60.seconds
)
Instance methods
Forces an immediate memory check.
Updates current statistics and triggers appropriate callbacks.
Returns
Current memory pressure level.
Example
pressure = limiter.check_now
puts "Current pressure: #{pressure}"
Checks if memory pressure is at critical level or higher.
Returns
true if usage >= critical_threshold, false otherwise.
Example
if limiter.critical?
cache.clear
GC.collect
end
Gets the current memory pressure level.
Returns
Current pressure level without forcing a new check.
Example
pressure = limiter.current_pressure
case pressure
when .warning?
puts "Memory usage is high"
when .critical?
puts "Memory usage is critical"
end
Checks if memory pressure is at emergency level.
Returns
true if usage >= emergency_threshold, false otherwise.
Example
if limiter.emergency?
raise "Out of memory!"
end
Starts monitoring memory usage in the background.
Creates a fiber that periodically checks memory usage and triggers callbacks based on threshold levels.
Example
limiter.start_monitoring
Gets a human-readable description of current memory state.
Returns
Description string.
Example
puts limiter.status_description
# => "Memory usage: 2.3 GB of 8.0 GB (28.8%) - Normal"
Suggests cache size based on current memory pressure.
Parameters
- max_size : Maximum desired cache size
Returns
Recommended cache size based on memory pressure.
Example
recommended = limiter.suggest_cache_size(1000)
cache.resize(recommended)
Checks if memory pressure is at warning level or higher.
Returns
true if usage >= warning_threshold, false otherwise.
Example
if limiter.warning?
cache.cleanup
end