Module: StateMachines::AsyncMode::ThreadSafeState

Defined in:
lib/state_machines/async_mode/thread_safe_state.rb

Overview

Thread-safe state operations for async-enabled state machines Uses concurrent-ruby for enterprise-grade thread safety

Instance Method Summary collapse

Instance Method Details

#marshal_dumpObject

Handle marshalling by excluding the mutex (will be recreated when needed)



32
33
34
35
36
# File 'lib/state_machines/async_mode/thread_safe_state.rb', line 32

def marshal_dump
  # Get instance variables excluding the mutex
  vars = instance_variables.reject { |var| var == :@_state_machine_mutex }
  vars.map { |var| [var, instance_variable_get(var)] }
end

#marshal_load(data) ⇒ Object

Restore marshalled object, mutex will be lazily recreated when needed



39
40
41
42
43
44
# File 'lib/state_machines/async_mode/thread_safe_state.rb', line 39

def marshal_load(data)
  data.each do |var, value|
    instance_variable_set(var, value)
  end
  # Don't set @_state_machine_mutex - let it be lazily created
end

#read_state_safely(machine, attribute, ivar = false) ⇒ Object

Thread-safe version of state reading Ensures atomic read operations across concurrent threads



17
18
19
20
21
# File 'lib/state_machines/async_mode/thread_safe_state.rb', line 17

def read_state_safely(machine, attribute, ivar = false)
  state_machine_mutex.with_read_lock do
    machine.read(self, attribute, ivar)
  end
end

#state_machine_mutexObject

Gets or creates a reentrant mutex for thread-safe state operations on an object Each object gets its own mutex to avoid global locking Uses Concurrent::ReentrantReadWriteLock for better performance



11
12
13
# File 'lib/state_machines/async_mode/thread_safe_state.rb', line 11

def state_machine_mutex
  @_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
end

#write_state_safely(machine, attribute, value, ivar = false) ⇒ Object

Thread-safe version of state writing Ensures atomic write operations across concurrent threads



25
26
27
28
29
# File 'lib/state_machines/async_mode/thread_safe_state.rb', line 25

def write_state_safely(machine, attribute, value, ivar = false)
  state_machine_mutex.with_write_lock do
    machine.write(self, attribute, value, ivar)
  end
end