Last active
January 3, 2016 19:39
-
-
Save numberoverzero/8510323 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
public interface Poolable<E> { | |
E getNext(); | |
void setNext(E next); | |
boolean isActive(); | |
E reset(); | |
} | |
public enum PoolBehavior { | |
EXPAND, | |
DESTROY, | |
NULL | |
} | |
// aka stack | |
public class PoolBuffer<E extends Poolable<E>> { | |
private E top; | |
public PoolBuffer() { | |
top = null; | |
} | |
public E push(E e) { | |
e.setNext(top); | |
top = e; | |
return top; | |
} | |
public E peek() { | |
return top; | |
} | |
public E pop() { | |
E tmp = top; | |
top = top.getNext(); | |
return tmp; | |
} | |
} | |
public class Pool<E extends Poolable<E>> { | |
private final PoolBuffer<E> buffer; | |
private final PoolBehavior behavior; | |
private final Callable<E> factory; | |
public Pool(int size, PoolBehavior behavior, Callable<E> factory) { | |
if (size < 1) { | |
throw new IllegalArgumentException("Invalid size " + size); | |
} | |
this.behavior = behavior; | |
this.factory = factory; | |
buffer = new PoolBuffer<>(); | |
E end = buffer.push(create()); | |
for (int i = 0; i < size - 1; i++) { | |
buffer.push(create()); | |
} | |
end.setNext(buffer.peek()); | |
} | |
protected E create() { | |
try { | |
return factory.call();e | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public E acquire() { | |
if (buffer.peek().isActive()) { | |
switch (behavior) { | |
case DESTROY: | |
// Ignore that it's active and reset it anyway | |
break; | |
case EXPAND: | |
release(create()); | |
break; | |
case NULL: | |
return null; | |
} | |
} | |
return buffer.pop().reset(); | |
} | |
public void release(E e) { | |
if (e == null) { | |
return; | |
} | |
assert !e.isActive(); | |
buffer.push(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment