Class: ThreadResourcePool

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/thread_resource_pool.rb

Overview

Copyright © 2007 FlexiGuided GmbH, Berlin

Author: Jan Behrens

Website: www.flexiguided.de/publications.flexirecord.en.html


ThreadResourcePool’s are pools of resources to be exclusively used by each thread of an application. They are abstract classes, and can’t be used directly. You have to create sub-classes, which implement the following three methods:

  • generate_resource

  • reset_resource

  • destroy_resource

Direct Known Subclasses

FlexiRecord::ConnectionPool

Instance Method Summary collapse

Instance Method Details

#current_resourceObject

Returns the resource being associated with the current thread, or nil there is none existing.



92
93
94
# File 'lib/thread_resource_pool.rb', line 92

def current_resource
  @resources_in_use[Thread.current]
end

#use_resourceObject

Checks if the current thread has already an associated resource, and either yields that resource or a newly generated or cached resource to the given block. If the thread had no resource associated at the time of call, the resource will be put back to the cache or destroyed when the block ends.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/thread_resource_pool.rb', line 97

def use_resource
  resource = self.current_resource
  unless resource.nil?
    return yield(resource)
  end
  begin
    begin
      resource = self.current_resource = get_new_resource
      return yield(resource)
    ensure
      self.current_resource = nil
    end
  ensure
    # if thread is terminated by force here, 'current_resource' has already been set to nil
    self.current_resource = nil
    put_resource_back(resource) unless resource.nil?
  end
end