/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.utils;
/**
* Stores a map of {@link ReflectionPool}s by type for convenient static access.
*
* @author Nathan Sweet
*/
public class Pools {
static private final ObjectMap<Class, ReflectionPool> typePools = new ObjectMap();
/**
* Returns a new or existing pool for the specified type, stored in a a Class to {@link ReflectionPool} map. The max
* size of the pool used is 100.
*/
static public <T> Pool<T> get(Class<T> type) {
ReflectionPool pool = typePools.get(type);
if (pool == null) {
pool = new ReflectionPool(type, 4, 100);
typePools.put(type, pool);
}
return pool;
}
/** Obtains an object from the {@link #get(Class) pool}. */
static public <T> T obtain(Class<T> type) {
return (T) get(type).obtain();
}
/** Frees an object from the {@link #get(Class) pool}. */
static public void free(Object object) {
if (object == null)
throw new IllegalArgumentException("object cannot be null.");
ReflectionPool pool = typePools.get(object.getClass());
if (pool == null)
throw new IllegalArgumentException("No objects have been obtained of type: " + object.getClass().getName());
pool.free(object);
}
/** Frees the specified objects from the {@link #get(Class) pool}. */
static public void freeAll(Array objects) {
if (objects == null)
throw new IllegalArgumentException("objects cannot be null.");
for (int i = 0, n = objects.size; i < n; i++) {
Object object = objects.get(i);
ReflectionPool pool = typePools.get(object.getClass());
if (pool == null)
throw new IllegalArgumentException("No objects have been obtained of type: "
+ object.getClass().getName());
pool.free(object);
}
}
private Pools() {
}
}