Skip to content

Instantly share code, notes, and snippets.

@OPhamster
Created July 14, 2018 08:31
Show Gist options
  • Save OPhamster/aed051a06a3b15c71e9a6e81a580d07d to your computer and use it in GitHub Desktop.
Save OPhamster/aed051a06a3b15c71e9a6e81a580d07d to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
class SafeHash < Hash
def initialize(namespace)
@namespace = namespace
@lock = Concurrent::ReadWriteLock.new
super
merge!({ @namespace => Concurrent::Map.new })
end
def []=(key, value)
fetch(@namespace, {})[key] = value
end
def [](key)
fetch(@namespace, {})[key]
end
def size
fetch(@namespace, {}).size
end
def keys
fetch(@namespace, {}).keys
end
def values
fetch(@namespace, {}).values
end
def clear
fetch(@namespace, {}).clear
end
def copy_and_clear
copy = {}
@lock.with_write_lock do
copy = delete(@namespace)
merge!({ @namespace => Concurrent::Map.new })
end
return copy
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment