Class: Shoryuken::Helpers::AtomicCounter
- Inherits:
-
Object
- Object
- Shoryuken::Helpers::AtomicCounter
- Defined in:
- lib/shoryuken/helpers/atomic_counter.rb
Overview
This class is optimized for scenarios with frequent atomic updates and occasional reads, such as tracking active worker counts.
A thread-safe counter implementation using Ruby’s Mutex.
This class provides atomic operations for incrementing, decrementing, and reading integer values in a thread-safe manner. It serves as a drop-in replacement for Concurrent::AtomicFixnum without requiring external dependencies.
The implementation uses a Mutex to ensure thread safety across all Ruby implementations including JRuby, where true parallelism makes atomic operations critical for data integrity.
Direct Known Subclasses
Instance Method Summary collapse
-
#decrement ⇒ Integer
Atomically decrements the counter by 1 and returns the new value.
-
#increment ⇒ Integer
Atomically increments the counter by 1 and returns the new value.
-
#initialize(initial_value = 0) ⇒ AtomicCounter
constructor
Creates a new atomic counter with the specified initial value.
-
#value ⇒ Integer
Returns the current value of the counter.
Constructor Details
#initialize(initial_value = 0) ⇒ AtomicCounter
Creates a new atomic counter with the specified initial value.
49 50 51 52 |
# File 'lib/shoryuken/helpers/atomic_counter.rb', line 49 def initialize(initial_value = 0) @mutex = Mutex.new @value = initial_value end |
Instance Method Details
#decrement ⇒ Integer
Atomically decrements the counter by 1 and returns the new value.
This operation is thread-safe and can be called concurrently from multiple threads without risk of data corruption or lost updates. The counter can go negative if decremented below zero.
99 100 101 |
# File 'lib/shoryuken/helpers/atomic_counter.rb', line 99 def decrement @mutex.synchronize { @value -= 1 } end |
#increment ⇒ Integer
Atomically increments the counter by 1 and returns the new value.
This operation is thread-safe and can be called concurrently from multiple threads without risk of data corruption or lost updates.
79 80 81 |
# File 'lib/shoryuken/helpers/atomic_counter.rb', line 79 def increment @mutex.synchronize { @value += 1 } end |
#value ⇒ Integer
Returns the current value of the counter.
This operation is thread-safe and will return a consistent value even when called concurrently with increment/decrement operations.
64 65 66 |
# File 'lib/shoryuken/helpers/atomic_counter.rb', line 64 def value @mutex.synchronize { @value } end |