import java.lang.reflect.Type;import org.apache.commons.pool2.impl.GenericObjectPool;import org.apache.commons.pool2.impl.GenericObjectPoolConfig;import com.google.gson.Gson;public class JsonPoolUtils { private static ThreadLocalinstance = new ThreadLocal (); protected static GenericObjectPool pool; static { if (instance.get() == null || pool == null) { GenericObjectPoolConfig conf = new GenericObjectPoolConfig(); conf.setMaxTotal(32); conf.setMaxIdle(4); pool = new GenericObjectPool (new PooledGsonFactory(), conf); } } public final static T fromJson(String json, Type typeOfT) { if (json == null) { return null; } Gson gson = null; try { gson = pool.borrowObject(); } catch (Exception e) { e.printStackTrace(); } T t = gson.fromJson(json, typeOfT); pool.returnObject(gson); return t; } public final static String toJson(Object src) { if (src == null) { return null; } Gson gson = null; try { gson = pool.borrowObject(); } catch (Exception e) { e.printStackTrace(); } String string = gson.toJson(src); pool.returnObject(gson); return string; }}
import java.sql.Timestamp;import org.apache.commons.pool2.BasePooledObjectFactory;import org.apache.commons.pool2.PooledObject;import org.apache.commons.pool2.impl.DefaultPooledObject;import com.google.gson.Gson;import com.google.gson.GsonBuilder;public class PooledGsonFactory extends BasePooledObjectFactory{ @Override public Gson create() throws Exception { return new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create(); } @Override public PooledObject wrap(Gson obj) { return new DefaultPooledObject (obj); }}