Created
September 19, 2012 18:35
-
-
Save Overbryd/3751359 to your computer and use it in GitHub Desktop.
A thread-safe state storage (intended to use with JRuby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # coding: utf-8 | |
| require "json" | |
| require "java" | |
| import "java.util.concurrent.ConcurrentHashMap" | |
| class Session | |
| def self.current | |
| @current ||= ConcurrentHashMap.new | |
| end | |
| def self.get(id) | |
| unless session = current.get(id) # get by id | |
| new_session = create(id) # but unless it exists, create one | |
| unless session = current.put_if_absent(id, new_session) # put it back | |
| session = new_session # but unless some other thread already put it first, use this one | |
| end | |
| end | |
| session | |
| end | |
| def self.create(id) | |
| data = JSON.parse(File.read("#{id}.json"), :symbolize_names => true) | |
| new(id, data) | |
| end | |
| # Blocking but thread-safe access to a session | |
| def self.with(id) | |
| get(id).lock.synchronize { yield session } | |
| end | |
| attr_reader :id, :lock | |
| def initialize(id, data) | |
| @id = id | |
| @data = data | |
| @lock = Mutex.new | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment