Class: Farce::Counter

Inherits:
Internal::Counter
  • Object
show all
Includes:
Abstract::Counter, Shareable::Native
Defined in:
lib/farce/counter.rb

Overview

Ractor-shareable, atomic counter. This is a stateful, numeric object.

Values are converted to Integers. On CRuby, the stored value and arithmetic deltas must fit in a signed 64-bit integer. An overflow raises RangeError without changing the stored value. Conditional-operation bounds may be wider, but a resulting stored value must still fit.

On CRuby, subclasses must not add Ruby instance variables.

Examples:

Allocate sequence numbers across threads or Ractors

counter = Farce::Counter.new
ticket = counter.increment # => 1
counter.increment          # => 2
ticket                     # => 1

Cross-Ractor counting

counter = Farce::Counter.new
counter.value # => 0

# Increase the counter by 1
counter.increment
counter.value # => 1

# Increase the counter by 5 on another Ractor
Ractor.new(counter) { it.add(5) }

# Give the other ractor time to run
sleep 0.1

counter.value # => 6

Counter as a numeric value

counter = Farce::Counter.new(10.0)
counter.to_i  # => 10
counter + 5   # => 15
2.5 * counter # => 25.0

require "active_support/all"
counter.minutes.to_i # => 600

Instance Method Summary collapse

Methods included from Shareable

#ractor_shareable?

Methods included from Abstract::Counter

#add, #decrement, #decrement_if_above, included, #increment, #increment_if_below, #initial, #reset, #update, #value, #wait_until, #wait_until_above, #wait_until_below, #wait_until_changed, #wait_until_match, #wait_until_value, #wait_while, #wait_while_above, #wait_while_below, #wait_while_match, #wait_while_value

Methods included from Internal::ValueSerialization

#as_extended_json, #as_json, #to_bson, #to_bson_normalized_value, #to_cbor, #to_json, #to_msgpack

Methods included from Abstract::Value

#blank?, #unwrap, #value

Methods included from Internal::Copyable

#duplicable?

Constructor Details

#initialize(value = 0) ⇒ Counter

Returns a new instance of Counter.

Parameters:

  • value (Numeric, String, #to_int) (defaults to: 0) —

    The initial value, converted to an Integer.

Raises:

  • (FrozenError)


51
52
53
54
# File 'lib/farce/counter.rb', line 51

def initialize(value = 0)
  raise FrozenError.new("can't initialize a frozen counter", receiver: self) if frozen?
  super(Integer(value))
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Farce::Abstract::Counter