Class: ThreadStore

Inherits:
Object
  • Object
show all
Defined in:
lib/xmpp4r/observable/thread_store.rb

Overview

XMPP4R - XMPP Library for Ruby

This file’s copyright © 2009 by Pablo Lorenzzoni <[email protected]>

License

Ruby’s license (see the LICENSE file) or GNU GPL, at your option.

Website::home.gna.org/xmpp4r/

Class ThreadStore

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max = 100) ⇒ ThreadStore

Create a new ThreadStore.

max

max number of threads to store (when exhausted, older threads will

just be killed and discarded). Default is 100. If 0 or negative no threads will be discarded until #keep is called.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/xmpp4r/observable/thread_store.rb', line 16

def initialize(max = 100)
  @store  = []
  @max    = max > 0 ? max : 0
  @cycles = 0
  @killer_thread = Thread.new do
    loop do
      sleep 2 while @store.empty?
      sleep 1
      @store.each_with_index do |thread, i|
        th = @store.delete_at(i) if thread.nil? or ! thread.alive?
        th = nil
      end
      @cycles += 1
    end
  end
end

Instance Attribute Details

#cyclesObject (readonly)

Returns the value of attribute cycles.



9
10
11
# File 'lib/xmpp4r/observable/thread_store.rb', line 9

def cycles
  @cycles
end

#maxObject (readonly)

Returns the value of attribute max.



9
10
11
# File 'lib/xmpp4r/observable/thread_store.rb', line 9

def max
  @max
end

Instance Method Details

#add(thread) ⇒ Object

Add a new thread to the ThreadStore



38
39
40
41
42
43
# File 'lib/xmpp4r/observable/thread_store.rb', line 38

def add(thread)
  if thread.instance_of?(Thread) and thread.respond_to?(:alive?)
    @store << thread
    keep(@max) if @max > 0
  end
end

#inspectObject

:nodoc:



33
34
35
# File 'lib/xmpp4r/observable/thread_store.rb', line 33

def inspect # :nodoc:
  sprintf("#<%s:0x%x @max=%d, @size=%d @cycles=%d>", self.class.name, __id__, @max, size, @cycles)
end

#keep(n = nil) ⇒ Object

Keep only the number passed of threads

n

number of threads to keep (default to @max if @max > 0)



48
49
50
51
52
53
54
# File 'lib/xmpp4r/observable/thread_store.rb', line 48

def keep(n = nil)
  if n.nil?
    raise ArgumentError, "You need to pass the number of threads to keep!" if @max == 0
    n = @max
  end
  @store.shift.kill while @store.length > n
end

#kill!Object

Kill all threads



57
58
59
# File 'lib/xmpp4r/observable/thread_store.rb', line 57

def kill!
  @store.shift.kill while @store.length > 0
end

#sizeObject

How long is our ThreadStore



62
# File 'lib/xmpp4r/observable/thread_store.rb', line 62

def size; @store.length; end