Class: Brown::Agent::Memo

Inherits:
Object
  • Object
show all
Defined in:
lib/brown/agent/memo.rb

Overview

:nodoc: A thread-safe agent “memo”.

This is the “behind the scenes” code that supports “agent memos”, objects which are shared across all instances of a given agent.

All of the interesting documentation about how agent memos work is in ClassMethods.memo and ClassMethods.safe_memo.

Instance Method Summary collapse

Constructor Details

#initialize(blk, safe = false, test = false) ⇒ Memo

Spawn a new memo.

Parameters:

  • blk (Proc)

    the block to call to get the value of the memo.

  • safe (Boolean) (defaults to: false)

    whether or not the value in the memo is inherently thread-safe for access. This should only be set when the object cannot be changed, or when the object has its own locking to protect against concurrent access. The default is to mark the memoised object as “unsafe”, in which case all access to the variable must be in a block, which is itself executed inside a mutex.



23
24
25
26
27
28
29
# File 'lib/brown/agent/memo.rb', line 23

def initialize(blk, safe=false, test=false)
	@blk         = blk
	@value_mutex = Mutex.new
	@attr_mutex  = Mutex.new
	@safe        = safe
	@test        = test
end

Instance Method Details

#value(test = nil) {|Object| ... } ⇒ Object?

Retrieve the value of the memo.

Yields:

  • (Object)

    the object which is the value of the memo.

Returns:

  • (Object, nil)

    if called without a block, this will return the object which is the value of the memo; otherwise, nil.

Raises:

  • (RuntimeError)

    if called on an unsafe memo without passing a block.



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/brown/agent/memo.rb', line 41

def value(test=nil)
	if block_given?
		@value_mutex.synchronize { yield cached_value }
		nil
	else
		if @safe || (@test && test == :test)
			cached_value
		else
			raise RuntimeError,
			      "Access to unsafe agent variable prohibited"
		end
	end
end