gpt4 book ai didi

java - 垃圾收集和异步调用/ future 对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:09:51 25 4
gpt4 key购买 nike

下面是一个利用 Future 接口(interface)进行异步调用的示例代码。我需要对 get() 方法进行一些说明。

Future<String> future = getAsyncString();
//do something ...
String msg = "";
if (validation)
return;
else
msg = future.get();
//do something else...
return;

future 变量是在方法中初始化的,所以该变量在方法执行后很快就会被 GC 清除,因为它不再被使用。那么如果代码进入 if 语句,JVM 会是什么状态?如果没有人要读回它,JVM 将如何处理包装的结果?它会影响 Thread Pool 或线程 Executor 吗?

最佳答案

How is the JVM going to handle the wrapped result in case that noone is going to read it back?

假设您从 Executor 获得了 Future 对象。为了让这个执行器能够在 Future 中设置结果,它持有对 Future 的引用。换句话说,仅仅因为对象的方法本地引用随着调用堆栈的弹出而消失,并不意味着 Future 对象(在堆上)自动符合垃圾回收条件。

异步调用没有被取消或类似的东西。执行者将执行调用,填写结果,并可能删除它对 Future 对象的引用。在此时,对象变得不可访问并符合垃圾回收条件。

如果您确定您的 代码没有保留对Future 对象的引用(即在//中泄漏它,请做一些事情.. . 部分)那么您可以确定 Future 对象(最终)被 GC 收集。 (执行器在这里没有任何细微的内存泄漏。)

[...] so the variable will be soon cleared by the GC.

准确地说,变量将随着调用堆栈的弹出而被丢弃。这最终将导致 Future object 无法访问并符合垃圾回收条件。然而,该对象通常不会在方法返回时立即被垃圾回收。

关于java - 垃圾收集和异步调用/ future 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30707155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com