Joao Pedrosa
Posts: 114
Nickname: dewd
Registered: Dec, 2005
Re: Considering Closures for Java
Posted: Dec 21, 2006 6:52 AM
Advertisement
His withLock example reminded of my newly updated DB Connection Pooling in Ruby. I think it's short enough to fit in this forum: require 'thread' module DR @pool_semaphore = Mutex.new @pools = {} @default_pool_conf = {:max => 10, :counter => 1, :timeout => 60 * 30} @pools_confs = {} def DR.pool_cycle ds, &block iface = ds.interface iface_sym = iface.symbol pool_key = [iface_sym, ds.db_str].inspect @pool_semaphore.synchronize{ pool = @pools[pool_key] if not pool @pools[pool_key] = {iface => Time.new} h = @default_pool_conf.clone @pools_confs[pool_key] = h else conf = @pools_confs[pool_key] keys = pool.keys if k = keys.find{|k| not pool[k] or pool[k] + conf[:timeout] < Time.new } iface = k ds.interface = k elsif conf[:counter] >= conf[:max] h = pool.invert oldest = h.keys.sort.last iface = h[oldest] ds.interface = iface else conf[:counter] += 1 db_str = ds.db_str.clone ds.interface = iface_sym iface = ds.interface iface.db_str = db_str end pool[iface] = Time.new end } iface.commit if block block[iface] DR.pool_return ds end iface end def DR.pool_return ds iface = ds.interface iface_sym = iface.symbol pool_key = [iface_sym, ds.db_str].inspect @pool_semaphore.synchronize{ @pools[pool_key][iface] = nil if @pools[pool_key][iface] } end end This is still very new (a couple of days only) and can grow in features over time. I did have some ideas of adding something like "withLock" more generic, but in Ruby it seems that that is unnecessary, being better to enjoy the delegation for each different algorithm/library. I hope this helps in giving some perspective to a very unusual subject.