java - Java中的线程何时从内存中删除?

标签 java memory memory-management garbage-collection jvm

来自 Java API 文档:

The Java Virtual Machine continues to execute threads until following occurs:

All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

我希望我的假设是正确的,一旦线程完成了它的 run() 方法,它就有资格进行垃圾收集。在同样的情况下,我只是想知道:

  1. 如果返回后不符合垃圾回收条件 从 run() 中,是否应该将其引用设置为 null 来做到这一点?
  2. 符合垃圾回收条件并不一定意味着 该对象将从内存中删除。它完全由 垃圾收集时的底层操作系统/JVM。 但是如何确保(通过 Java 程序或外部工具)对象已完全从 内存?
  3. 如果一个线程一旦完成它的 run() 方法就被认为是死的,为什么 我还能在 同一个线程对象?两个调用都返回 falseRUNNABLE 分别。

最佳答案

Thread 类是 native 内存中真实线程的代理。

I hope my assumption is correct that once thread finishes its run() method it becomes eligible for garbage collection.

run()之后其实有一段代码,这段代码处理未捕获的异常。

一旦线程死亡,它的 native 内存和堆栈会立即释放,无需 GC。然而,Thread 对象就像任何其他对象一样,它一直存在,直到 GC 决定它可以是免费的,例如没有强烈的引用。

同样,FileOutputStream 是操作系统中文件的代理。即使文件已被 close() 甚至删除,您仍然可以引用该对象。

If it doesn't become eligible for garbage collection after returning from run(), should one set its reference to null to do that?

您很少需要在任何地方执行此操作。事实上,首先不保留对线程的引用,或者使用 ExecutorService 来管理线程通常更简单。

当我有一个具有 Thread 字段的对象时,我经常在线程终止时使该对象终止,因此该字段不需要 nulled out .

我还使用用于 Fork/Join 的内置线程池。这是一种在后台线程中执行任务的更轻量级的方法,因为它不会创建和销毁线程。

ExecutorService fjp = ForkJoinPool.commonPool();

Being eligible for garbage collection doesn't necessarily mean that the object will be removed from memory. It is at the sole discretion of the underlying operating system / JVM when it is garbage collected. But how can one make sure (either through a Java program or external tool) that the object is completely removed from the memory?

您不能也通常不应该尝试。 GC 会在需要时清理资源。

If a thread is said to be dead once it finishes its run() method, why can I still be able to execute isAlive() or getState() on the same thread object? Both the calls return false and RUNNABLE respectively.

线程对象与任何其他对象一样。只要您持有对它的引用,就可以对其调用方法。

关于java - Java中的线程何时从内存中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28319636/

相关文章:

java - 如何获取 Hibernate 查询结果作为列表或 HashMap 的关联数组

java - JAVA 为堆栈上的对象而不是堆上的对象预分配内存

c++ - 返回分配的局部变量

iphone - 奇怪的 Objective-C 问题

objective-c - 在 Objective-C 中初始化结构数组

java - java中一种产品的库存只减少?

java - 制作类的全局实例 - JAVA

iphone - UITableView 图像 - 保存两个图像或调整大小?

multithreading - Perl 脚本随着进度变慢

java - JVM性能调优: young copy vs old generation gc