为什么for循环会导致JVM逃脱失败

发布于 2025-01-26 06:44:50 字数 767 浏览 2 评论 0原文

添加一个用于循环时,逃生失败。 JVM内存GC经常

在表面上,CTX字段应成功逃脱。

但是,当CTX在for循环之前和之后时,它的结果不同。

我不确定JVM的详细实现,但是没有地方可以解释逃生失败的原因。

JVM8和14都尝试过,结果是相同的。

有人可以告诉我为什么吗?

class Ctx {
    private String name;

     public Ctx(String name) {
         this.name = name;
     }

     public String getName() {
         return name;
     }

     public void doNothing() {

     }
 }

public class Test {
    public static void main(String[] args) {
        for (long i = 0; i < Long.MAX_VALUE; ++i) {
            Ctx ctx = new Ctx("name");
            // escape success
            ctx.doNothing();
            for (int c = 0; c < 4; c++) {

            }
            // escape fail
            // ctx.doNothing();
        }
    }
}

When a for loop is added, the escape fails. JVM memory GC frequently。

On the surface, the CTX field should escape successfully.

However, when CTX is before and after the for loop, it has different results.

I'm not sure about the detailed implementation of the JVM, but there is no place to explain the reasons for the escape failure.

Both jvm8 and 14 have tried, and the result is the same.

Can someone tell me why?

class Ctx {
    private String name;

     public Ctx(String name) {
         this.name = name;
     }

     public String getName() {
         return name;
     }

     public void doNothing() {

     }
 }

public class Test {
    public static void main(String[] args) {
        for (long i = 0; i < Long.MAX_VALUE; ++i) {
            Ctx ctx = new Ctx("name");
            // escape success
            ctx.doNothing();
            for (int c = 0; c < 4; c++) {

            }
            // escape fail
            // ctx.doNothing();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文