简体   繁体   English

Java线程和垃圾回收

[英]Java Threads and Garbage Collection

I have read in countless places that running threads are garbage collection roots (ie they reside on the stack, the GC identifies them and traces through them to determine if the objects inside them are still reachable). 我已经在无数地方阅读到运行线程是垃圾回收根(即它们驻留在堆栈上,GC会识别它们并跟踪它们以确定它们中的对象是否仍然可以访问)。 Further more, a GC root will never be garbage collected itself. 此外,GC根本身将永远不会被垃圾回收。

My confusion is here: If the objects allocated from within a thread can never be garbage collected until the thread is stopped, how then is anything garbage collected in single-threaded programs where the only thread is the main thread ? 我的困惑在这里:如果从一个线程中分配的对象在线程停止之前永远不会被垃圾回收,那么,在唯一线程是主线程的单线程程序中,又如何垃圾回收呢?

Clearly I'm missing something here. 显然我在这里缺少什么。

Objects are in the heap, regardless which thread created them. 对象是在堆中,而不管是由哪个线程创建的。

Objects may be reachable through references . 通过引用可以达到对象。 Some of these references can be on the call stack of one or more threads. 其中一些引用可以在一个或多个线程的调用堆栈上。

An object can be collected when there are no more references to it, regardless whether is allocating thread is still running or not. 如果没有更多引用,则可以收集对象,无论分配线程是否仍在运行。

For example, the thread below repeatedly allocates new StringBuilder objects. 例如,下面的线程反复分配新的StringBuilder对象。 During a call to foo(), the thread has references on its call stack to a StringBuilder object. 在对foo()的调用期间,线程在其调用堆栈上具有对StringBuilder对象的引用。 When foo() returns, there are no further references to the StringBuilder object. foo()返回时,没有对StringBuilder对象的进一步引用。 Therefore, that object is no longer reachable, and is eligible for garbage collection. 因此,对象不再可达,并有资格进行垃圾回收。

Thread thread = new Thread( new Runnable() {
    @Override
    public void run() {
        while ( true ) {
            foo();
        }
    }

    public void foo() {
        StringBuilder strBuilder = new StringBuilder("This new object is allocated on the heap.");
        System.out.println( strBuilder );
    }
});

thread.run();

First, a thread (stack) is only a GC root while it is alive. 首先,线程(堆栈)在运行时只是GC的根。 When the thread terminates, it is no longer a GC root. 当线程终止时,它不再是GC根。

My confusion is here: If the objects allocated from within a thread can never be garbage collected until the thread is stopped, how then is anything garbage collected in single-threaded programs where the only thread is the main thread ? 我的困惑在这里:如果从一个线程中分配的对象在线程停止之前永远不会被垃圾回收,那么,在唯一线程是主线程的单线程程序中,又如何垃圾回收呢?

Your premise is incorrect. 您的前提不正确。

It doesn't matter which thread allocates an object. 哪个线程分配对象都没有关系。 What matters is whether an objects allocated by your thread remains reachable . 重要的是线程分配的对象是否仍然可以访问 If it become unreachable (for example, if you didn't put the object's reference into a local variable) ... then it can be collected. 如果它变得不可访问(例如,如果您没有将对象的引用放入局部变量中)...则可以对其进行收集。

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

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