是否可以使用 try-catch 语句修补内存泄漏?

发布于 2024-09-28 09:21:26 字数 353 浏览 8 评论 0原文

     if(pCoeff.size()>thisCoeff.size()){
        difference=pCoeff.size()-thisCoeff.size();
        for(int i=thisCoeff.size(); i<thisCoeff.size()+difference;i++){

            thisCoeff.add(i, new Double(0.0)); //this line throws errors
        }
     } 

我已将程序的这部分隔离为内存泄漏的原因,是否可以使用 try catch 语句来修补此问题?如果是这样,语法是什么?

     if(pCoeff.size()>thisCoeff.size()){
        difference=pCoeff.size()-thisCoeff.size();
        for(int i=thisCoeff.size(); i<thisCoeff.size()+difference;i++){

            thisCoeff.add(i, new Double(0.0)); //this line throws errors
        }
     } 

I've isolated this portion of my program as being the cause of memory leak, is it possible to patch this using a try catch statement? If so, what is the syntax?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

漫雪独思 2024-10-05 09:21:26

是否可以使用 try catch 语句来修补此问题?

一般来说,没有。

不过,我想我可以看到你的问题的原因。基本上,循环永远不会终止。每次循环时,都会向集合中添加一个新对象。这会将 thisCoeff.size() 返回的值增加一。以下修复解决了这个问题:

if (pCoeff.size() > thisCoeff.size()) {
    difference = pCoeff.size() - thisCoeff.size();
    int limit = thisCoeff.size() + difference;
    for (int i = thisCoeff.size(); i < limit; i++) {
        thisCoeff.add(i, new Double(0.0));
    }
}

is it possible to patch this using a try catch statement?

In general, no.

However, I think I can see the cause of your problem. Basically, tbe loop will never terminate. Each time you go around the loop, you add a new object to the collection. This increases the value returned by thisCoeff.size() by one. The following fix addresses this:

if (pCoeff.size() > thisCoeff.size()) {
    difference = pCoeff.size() - thisCoeff.size();
    int limit = thisCoeff.size() + difference;
    for (int i = thisCoeff.size(); i < limit; i++) {
        thisCoeff.add(i, new Double(0.0));
    }
}
久随 2024-10-05 09:21:26

不,唯一的方法是让 catch 语句中的某些内容变得无法访问,然后进行垃圾收集。

在这种情况下,假设 .size() 方法没有执行任何意外操作,内存使用量来自所有这些 Double 对象,您可以通过仅使用一个 Double 对象作为静态常量来获得巨大的内存改进,并添加将其添加到集合中,或者让 jvm 自动装箱。

No, the only way to do that is to have something become unreachable in the catch statement than can then be garbage collected.

In this case, assuming that the .size() methods don't do anything unexpected, the memory usage comes from all of those double objects, you can gain a huge memory improvement by using only one Double object as a static constant, and adding it to the collection, or letting the jvm autobox for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文