Class: N::SafeHashDelegator

Inherits:
Hash
  • Object
show all
Defined in:
lib/glue/hash.rb

Overview

SafeHashDelegator

A thread-safe hash. We use a sync object instead of a mutex, because it is re-entrant. An exclusive lock is needed when writing, a shared lock IS NEEDED when reading

Design: This class uses the delegator pattern. However we dont use rubys delegation facilities, they are more general and powerfull than we need here (and slower). Instead a custom (but simple) solution is used.

Example:

hash = SafeHashDelegator.new(Hash.new) hash = SafeHashDelegator.new(Hash.new)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(delegate) ⇒ SafeHashDelegator

Returns a new instance of SafeHashDelegator.



94
95
96
97
# File 'lib/glue/hash.rb', line 94

def initialize(delegate)
	@delegate = delegate
	@sync = ::Sync.new
end

Instance Attribute Details

#delegateObject (readonly)

Returns the value of attribute delegate.



92
93
94
# File 'lib/glue/hash.rb', line 92

def delegate
  @delegate
end

Instance Method Details

#[](key) ⇒ Object



99
100
101
102
103
# File 'lib/glue/hash.rb', line 99

def [](key)
		return @sync.synchronize(::Sync::SH) {
			@delegate[key]
		}
end

#[]=(key, value) ⇒ Object



105
106
107
108
109
# File 'lib/glue/hash.rb', line 105

def []=(key, value)
		return @sync.synchronize(::Sync::EX) {
			@delegate[key] = value
		}
end

#clearObject



117
118
119
120
121
# File 'lib/glue/hash.rb', line 117

def clear
	@sync.synchronize(::Sync::EX) {
		@delegate.clear
	}
end

#delete(key) ⇒ Object



111
112
113
114
115
# File 'lib/glue/hash.rb', line 111

def delete(key)
	return @sync.synchronize(::Sync::EX) {
		@delegate.delete(key)
	}
end

#keysObject



135
136
137
138
139
# File 'lib/glue/hash.rb', line 135

def keys
	return @sync.synchronize(::Sync::SH) {
		@delegate.keys()
	}
end

#sizeObject



123
124
125
126
127
# File 'lib/glue/hash.rb', line 123

def size
	return @sync.synchronize(::Sync::SH) {
		@delegate.size()
	}
end

#valuesObject



129
130
131
132
133
# File 'lib/glue/hash.rb', line 129

def values
	return @sync.synchronize(::Sync::SH) {
		@delegate.values()
	}
end