package electrosphere.client.terrain.data;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Pools allocated terrain chunk data objects
 */
public class TerrainChunkDataPool {

    /**
     * Structure to store not-in-use objects
     */
    static List<TerrainChunkData> pool = new LinkedList<TerrainChunkData>();

    /**
     * Lock for thread-safeing operations
     */
    static ReentrantLock lock = new ReentrantLock();

    /**
     * Gets a terrain chunk object from the pool. Allocates if no free one is available.
     * @return A terrain chunk object of the requested type
     */
    public static TerrainChunkData get(){
        TerrainChunkData rVal = null;
        lock.lock();
        if(pool.size() > 0){
            rVal = pool.remove(0);
        } else {
            rVal = new TerrainChunkData();
        }
        lock.unlock();
        return rVal;
    }

    /**
     * Releases a terrain chunk data object back into the pool
     * @param data The object to release
     */
    public static void release(TerrainChunkData data){
        lock.lock();
        TerrainChunkDataPool.pool.add(data);
        lock.unlock();
    }
    
}
