简体   繁体   English

Java-GC是否会再尝试一次以释放内存?

[英]java - does GC try more then once to release memory?

Lets say i have a asyncTask like this: 可以说我有一个asyncTask像这样:

 public void startAsyncTask() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {

                try {
                    Thread.sleep(300000);
                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
                return null;
            }
        }.execute();
    }

For those who dont know a asyncTask just creates a background thread. 对于那些不知道asyncTask的人,只会创建一个后台线程。 and anonymous classes are really non-static inner classes. 匿名类实际上是非静态内部类。

Now lets say in the activity (main thread) i call startAsyncTask() 现在在活动(主线程)中说我调用startAsyncTask()

the thread will take a little while to complete (about 5 minutes). 该线程将需要一些时间才能完成(大约5分钟)。

During the background threads lifetime, lets imagine the activity gets destroyed and its time to garbage collect the activity. 在后台线程生命周期中,让我们想象一下活动被销毁了,并且浪费了时间来收集活动。 Since the asyncTask has an implicit reference to the outer class (the activity) the activity will leak and will not be garbage collected. 由于asyncTask具有对外部类(活动)的隐式引用,因此该活动将泄漏并且不会被垃圾收集。

But my question is the following: After some time, the child thread will eventually finish. 但是我的问题是:一段时间后,子线程将最终完成。 Can the GC attempt to free memory again or is the activity forever leaked ? GC可以再次尝试释放内存吗?还是活动永远泄漏了? What i want to know really is if the child thread finishes in a reasonable amount of time will the activities memory be freed or is it only on the first attempt the GC tries and after that attempt the memory is forever lost ? 我真正想知道的是,如果子线程在合理的时间内完成,活动内存将被释放,还是仅在第一次尝试GC时尝试,然后再永久丢失该内存?

The garbage collector does not operate based on the activity life-cycle, it operates based on "are there any objects referencing it". 垃圾收集器不基于活动生命周期进行操作,而是基于“是否有任何引用它的对象”进行操作。 So yeah, the activity memory will be freed after the thread finishes (and the AsyncTask is not referencing it anymore). 因此,是的,活动内存将在线程完成后被释放(并且AsyncTask不再引用它了)。

But that still is a memory leak of a very heavy object (the activity). 但这仍然是一个非常重的对象(活动)的内存泄漏。 And it's bad programming that shouldn't be done. 这是不应该做的不好的编程。

I'm not sure if you have an actual problem that you want to apply that, or is that a purely theoretical question on the inner workins of the VM, but if it's an actual problem that you want to apply that; 我不确定您是否有要应用的实际问题,还是对VM的内部工作原理的纯粹理论上的问题,但是如果您是要解决的实际问题,则不确定。 the answer is: Don't do it! 答案是: 不要这样做!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM