mogilefs-client.git  about / heads / tags
MogileFS client library for Ruby
blob 390e4a97f13372104ee2677971421ab1fbefbcb9 1086 bytes (raw)
$ git show HEAD:lib/mogilefs/pool.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
# -*- encoding: binary -*-
require 'thread'

class MogileFS::Pool

  # Must be a positive Integer that is greater than :purge_keep
  # Default: 5
  attr_accessor :purge_threshold

  # Must be a positive Integer that is smaller than :purge_threshold
  # Default: 2
  attr_accessor :purge_keep

  BadObjectError = Class.new(RuntimeError)

  def initialize(klass, *args)
    @args = args
    @klass = klass
    @queue = Queue.new
    @objects = {}
    @purge_threshold = 5
    @purge_keep = 2
  end

  def get
    @queue.pop true
  rescue ThreadError
    object = @klass.new(*@args)
    @objects[object] = object
  end

  def put(o)
    raise BadObjectError unless @objects.include? o
    @queue.push o
    purge
  end

  def use
    object = get
    yield object
    nil
  ensure
    put object
    nil
  end

  def purge
    return if @queue.length < @purge_threshold
    begin
      until @queue.length <= @purge_keep
        obj = @queue.pop true
        @objects.delete obj
        obj.backend.shutdown if MogileFS::Client === obj
      end
    rescue ThreadError
    end
  end

end


git clone https://yhbt.net/mogilefs-client.git