Created
October 26, 2023 07:21
-
-
Save fourlastor/90d0bc6dc55e3fbb3d84985750ef0c20 to your computer and use it in GitHub Desktop.
Auto poolable
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
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 | |
); | |
} | |
} |
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
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; | |
} | |
} |
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
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