0

我有几个经常与服务通信的类。消息发送使用

private void sendMessage(int what)
{
    Message msg = Message.obtain(null, what);
    try
    {
        mServerMessenger.send(msg);
    }
    catch (RemoteException e)
    {

    }
}  

我的问题是

  • 我应该声明一个类成员Message mMessage而不是在本地声明它。

  • 如果声明为类成员,我应该使用Message constructor or 使用Message.obtain.

  • 作为班级成员recycleonDestroy如果使用 Message.obtain.

到目前为止,我没有遇到任何内存问题,但我想尽可能有效地使用系统资源。

4

1 回答 1

1

这将是我的 2c:

1)我应该声明一个类成员 Message mMessage 而不是在本地声明它。

我想要一个类成员,这样 JVM 就不必在每次方法调用时为局部变量创建条目。

2) 如果声明为类成员,我应该使用 Message 构造函数还是使用 Message.obtain。

始终使用obtain(),因为它使用对象池..

onDestroy3) 作为班级成员,如果使用 Message.obtain ,我是否需要调用回收。

你不需要调用 recycle只是nullify.class variable

您可以查看Message.java源以获取更多信息..

如果我发现更多内容,我也会仔细阅读并更新帖子。

编辑1:

我再次要求您检查源代码。recycle()如果要将对象返回给该方法,则应global object pool调用该方法。在调用回收方法后不应使用该对象。复制该方法(ICS)以供快速参考:

/**
 * Return a Message instance to the global pool.  You MUST NOT touch
 * the Message after calling this function -- it has effectively been
 * freed.
 */
public void recycle() {
    clearForRecycle();

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

只要您不调用“recyle()”,您就可以使用该实例。因此,如果在代码中调用方法recycle()之前调用是一个好习惯。在调用和对象中调用。obtain()onDestroy()recycle()nullify

于 2013-04-29T07:32:18.047 回答