Created
May 17, 2011 17:40
-
-
Save duckinator/976940 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2010 Nick Markwell | |
* | |
* This is released under the MIT/X11 license. | |
* See COPYING | |
*/ | |
import structs/ArrayList | |
/** | |
* ObjectPool new(min, max: Int, reset: Func) | |
* - min is a used_objects/total_objects ratio which must be less than | |
* used size/(used size + free size) | |
* - max is a used_objects/total_objects ratio which must be greater than | |
* used size/(used size + free size) | |
* - reset is a function/closure which specifies what to do to reset each object, | |
* it is passed a single variable, which is the object to be reset | |
* If the reset block is not defined, it is assumed the object does not need resetting. | |
*/ | |
ObjectPool: class<T> { | |
min, max: SizeT | |
used := ArrayList<T> new() | |
free := ArrayList<T> new() | |
_reset: Func(T) | |
init: func (=min, =max, fn: Func(T)) { | |
_reset = fn | |
} | |
init: func ~noReset(=min, =max) { | |
free add(T alloc()) | |
} | |
ratio: func -> SizeT { | |
used size/(used size + free size) | |
} | |
reset: func(obj: T) { | |
if((_reset as Closure) thunk != null) { | |
_reset(obj) | |
} | |
} | |
use: func -> T { | |
if(min >= ratio) | |
free add(T alloc()) | |
used add(free[0]) | |
free removeAt(0) | |
used[-1] | |
} | |
free: func(obj: T) -> T { | |
reset(obj) | |
free add(obj) | |
used remove(obj) | |
while (max <= ratio() && ratio() > 0) { | |
free removeAt(-1) | |
} | |
obj | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment