Class: Threadz::AtomicInteger
- Inherits:
-
Object
- Object
- Threadz::AtomicInteger
- Defined in:
- lib/threadz/atomic_integer.rb
Overview
Related to, or at least named after, Java’s AtomicInteger. Provides a thread-safe integer counter thing. The code used in this file, while slightly verbose, is to optimize performance. Avoiding additional method calls and blocks is preferred.
Instance Method Summary collapse
- #decrement(amount = 1) ⇒ Object
- #increment(amount = 1) ⇒ Object
-
#initialize(value) ⇒ AtomicInteger
constructor
A new instance of AtomicInteger.
- #set(value) ⇒ Object
- #value ⇒ Object
Constructor Details
#initialize(value) ⇒ AtomicInteger
Returns a new instance of AtomicInteger.
9 10 11 12 |
# File 'lib/threadz/atomic_integer.rb', line 9 def initialize(value) @value = value @mutex = Mutex.new end |
Instance Method Details
#decrement(amount = 1) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/threadz/atomic_integer.rb', line 26 def decrement(amount=1) # We could refactor and just call set here, but it's faster just to write # the extra two lines. @mutex.lock @value -= amount @mutex.unlock end |
#increment(amount = 1) ⇒ Object
18 19 20 21 22 23 24 |
# File 'lib/threadz/atomic_integer.rb', line 18 def increment(amount=1) # We could use Mutex#synchronize here, but compared to modifying an # integer, creating a block is crazy expensive @mutex.lock @value += amount @mutex.unlock end |
#set(value) ⇒ Object
34 35 36 37 38 |
# File 'lib/threadz/atomic_integer.rb', line 34 def set(value) @mutex.lock @value = value @mutex.unlock end |
#value ⇒ Object
14 15 16 |
# File 'lib/threadz/atomic_integer.rb', line 14 def value @value end |