Skip to content

Instantly share code, notes, and snippets.

@fourlastor
Created October 26, 2023 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fourlastor/90d0bc6dc55e3fbb3d84985750ef0c20 to your computer and use it in GitHub Desktop.
Save fourlastor/90d0bc6dc55e3fbb3d84985750ef0c20 to your computer and use it in GitHub Desktop.
Auto poolable
package io.github.fourlastor.pool;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.utils.Pools;
public class AutoPool<T> extends Pool<AutoPoolable<T>> {
private final Pool<T> pool;
public AutoPool(Class<T> type) {
this(Pools.get(type, 15));
}
public AutoPool(Pool<T> pool) {
this.pool = pool;
}
@Override
public AutoPoolable<T> obtain() {
AutoPoolable<T> poolable = super.obtain();
poolable.set(pool.obtain());
return poolable;
}
@Override
protected AutoPoolable<T> newObject() {
return new AutoPoolable<>(
this,
pool
);
}
}
package io.github.fourlastor.pool;
import com.badlogic.gdx.utils.Pool;
public class AutoPoolable<T> implements AutoCloseable, Pool.Poolable {
private final Pool<AutoPoolable<T>> pool;
private final Pool<T> tPool;
private T t;
public AutoPoolable(Pool<AutoPoolable<T>> pool, Pool<T> tPool) {
this.pool = pool;
this.tPool = tPool;
}
@Override
public void close() {
pool.free(this);
}
public T get() {
return t;
}
void set(T t) {
this.t = t;
}
@Override
public void reset() {
tPool.free(t);
t = null;
}
}
package io.github.fourlastor.pool;
import com.badlogic.gdx.math.Vector2;
public class Example {
public static void example(AutoPool<Vector2> pool) {
try (AutoPoolable<Vector2> it = pool.obtain()) {
Vector2 vector2 = it.get(); // pooled and cleaned at the end of block
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment