Synch ronized Poolオブジェクトプール使用-Android

1336 ワード

メモリ最適化では、あるオブジェクトが常に作成されている場合、メモリ資源が非常に損失されます.masageオブジェクトはよく使用されます.彼はオブジェクトを取得するために、obtain()方法を提供します.彼は毎回オブジェクトを作成するのではなく、オブジェクトプールを使って保存します.次の使用先のプール:
package com.example.xieqiping.cn.testdomejsonliyihang;

import android.support.v4.util.Pools;
import android.util.Log;

/**
 * Created by xieqiping on 2017/4/9.
 */
public class TestClass {

    public String name="TestClass";

    static final String tag="TestClass";

    private static final Pools.SynchronizedPool sPool=new Pools.SynchronizedPool(1);//   

    //       
    public static TestClass obtain(){
        TestClass acquire = sPool.acquire();
        if (acquire==null){
            Log.i(tag, "init class");
            return new TestClass();
        }
        return acquire;
    }

    //    
    public void recycle(){
        sPool.release(this);
    }

}

呼び出しテスト:

        TestClass testClass = new TestClass();
        Log.i(TAG, "name: "+testClass.name);
        testClass.name="new name";
        testClass.recycle();//       
        TestClass obtain = TestClass.obtain();
        Log.i(TAG, "name: "+obtain.name);
        TestClass obtain1 = TestClass.obtain();
        Log.i(TAG, "name: "+obtain1.name);