1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
35 """Classes to support pools of arbitrary objects.
37 The :class:`ObjectPool` class in this module abstracts a pool
38 of arbitrary objects. Subclasses need to define the details regarding
39 creation, destruction, allocation and release of their specific objects.
43 # This should work under gevent, because gevent monkey patches 'threading'
44 # if not, we can detect if running under gevent, e.g. using
45 # if 'gevent' in sys.modules:
46 # from gevent.coros import Semaphore
48 # from threading import Semaphore
49 from threading import Semaphore, Lock
52 __all__ = ['ObjectPool', 'ObjectPoolError', 'PoolEmptyError']
55 class ObjectPoolError(Exception):
59 class PoolEmptyError(ObjectPoolError):
63 class ObjectPool(object):
64 def __init__(self, size=None):
69 raise ValueError("Invalid size for pool (positive integer "
70 "required): %r" % (size,))
72 self._semaphore = Semaphore(size) # Pool grows up to size
73 self._mutex = Lock() # Protect shared _set oject
76 def pool_get(self, blocking=True, timeout=None, create=True):
77 """Get an object from the pool.
79 Get an object from the pool. By default (create=True), create a new
80 object if the pool has not reached its maximum size yet. If
81 create == False, the caller is responsible for creating the object and
82 put()ting it back into the pool when done.
85 # timeout argument only supported by gevent and py3k variants
86 # of Semaphore. acquire() will raise TypeError if timeout
87 # is specified but not supported by the underlying implementation.
88 kw = {"blocking": blocking}
89 if timeout is not None:
90 kw["timeout"] = timeout
91 r = self._semaphore.acquire(**kw)
93 raise PoolEmptyError()
99 obj = self._pool_create() if create else None
101 self._semaphore.release()
103 # We keep _semaphore locked, put() will release it
106 def pool_put(self, obj):
107 """Put an object back into the pool.
109 Return an object to the pool, for subsequent retrieval
110 by pool_get() calls. If _pool_cleanup() returns True,
111 the object has died and is not put back into self._set.
115 if not self._pool_cleanup(obj):
117 self._semaphore.release()
119 def _pool_create(self):
120 """Create a new object to be used with this pool.
122 Create a new object to be used with this pool,
123 should be overriden in subclasses.
126 raise NotImplementedError
128 def _pool_cleanup(self, obj):
129 """Cleanup an object before being put back into the pool.
131 Cleanup an object before it can be put back into the pull,
132 ensure it is in a stable, reusable state.
135 raise NotImplementedError