【问题标题】:Allocate and deallocate memory to static method为静态方法分配和释放内存
【发布时间】:2014-12-10 11:19:56
【问题描述】:

您能否描述一下我调用静态方法时为它分配和释放内存的过程?

public class Class1 {

    public static ArrayList<String> method1(Context context) {
        // some variables
        return new ArrayList<String>();
    }

}

我在 Class1 中编写了一个简单的静态方法示例,该方法在无限期工作的服务中调用!
现在我想知道垃圾收集器是否从内存中删除了此方法?
我研究过静态变量,一旦类加载器从内存中删除,静态变量就会被删除。但是方法呢?
抱歉,我知道我的问题不清楚,但我的意思是标题。

public class TestService extends IntentService {

    public TestService() {
        super("test");
    }

    @Override
    protected void onHandleIntent(Intent intent) {  
        while(true){
            Class1.method1(this);
        }
    }
}

【问题讨论】:

    标签: java android memory-management static


    【解决方案1】:

    如果你在堆上分配了一些东西,并丢弃了对它的引用,内存将被垃圾收集器释放。

    while(true) {
        // Allocate a new ArrayList, throw away the return value (a no-op)
        Class1.method1(this);
    }
    

    【讨论】:

    • 您的意思是垃圾收集器从内存中删除的方法返回值直到下一个循环?还有它的参数和内部方法变量?
    • method1 返回对堆上 ArrayList 的引用。如果您丢弃该引用,则无法再访问该 ArrayList,并且垃圾收集器将为该 ArrayList 释放内存。参数和方法局部变量存储在堆栈中,并在方法返回时释放。
    猜你喜欢
    • 2013-08-29
    • 2016-01-26
    • 2011-12-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2011-03-17
    相关资源
    最近更新 更多