2
\$\begingroup\$

I've done some code so you can obtain Object of any Class from Pool, take a look at it, is it safe? At least it works.

MultiPool class has method obtain with Class param, so can know from which inner-pool obtain Object.

import com.badlogic.gdx.utils.Pool;

import java.lang.reflect.Modifier;
import java.util.HashMap;

public class MultiPool {
    public class MultiPoolException extends Exception {
        public MultiPoolException(String message) {
            super(message);
        }
    }

    public class AnyPool extends Pool<Object> {
        Class<?> type;

        AnyPool(Class<?> type) {
            this.type = type;
        }

        @Override
        protected Object newObject() {
            try {
                return type.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    HashMap<Class<?>, AnyPool> pools = new HashMap<Class<?>, AnyPool>();

    private void initializePool(Class<?> type) {
        pools.put(type, new AnyPool(type));
    }

    @SuppressWarnings("unchecked")
    public <T> T obtain(Class<?> type) {
        if ( Modifier.isAbstract(type.getModifiers()) ) {
            (new MultiPoolException(type.getName() + " is abstract.")).printStackTrace();
            return null;
        }

        if ( pools.get(type) == null ) initializePool(type);

        return (T) pools.get(type).obtain();
    }

    public void free(Object object) {
        Class<?> type = object.getClass();

        if ( pools.get(type) == null ) initializePool(type);

        pools.get(type).free(object);
    }
}

Usage:

MultiPool multiPool = new MultiPool();

String abc = multiPool.obtain(String.class);
SomeOtherClass test = multiPool.obtain(SomeOtherClass.class);

multiPool.free(test);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.