0

我的应用程序每天发出数百个新的连接请求并解析 json 响应。但我意识到它不会在每次请求后释放内存。尽管使用 system.gc() 它存储 ConnectionRequest 实例和我的类的实例以解析 json 响应。我猜最后它会导致系统内存不足错误。

这是一些代码:

  protected boolean onMainFormCommand54(){
         //LevakandRestService similar to GoogleRestService
        final LevakandRestService r =new LevakandRestService();
        r.RequestUBalance(balance);        
        final Progress p = new Progress(Globals.Loading, r);
        p.showPacked(BorderLayout.CENTER, false);
        p.setDisposeOnCompletion(true);
        r.addResponseListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {                            
                    p.dispose();                                      
                    Dialog.show(Globals.Info, "Balance:" +balance.getBalance(),Globals.OK, "");
            }
        });
       NetworkManager.getInstance().addToQueueAndWait(r);

       System.gc(); 
      return val;
  }

我试过使用 Wea​​kReference,但没有帮助。

 protected boolean onMainFormCommand54() {//Balance of user

    boolean val = super.onMainFormCommand54();       
    Balance balance1 = new Balance();
    WeakReference wrb = new WeakReference(balance1);       
    final Balance balance =(Balance)wrb.get();
        LevakandRestService r1 = new LevakandRestService();            
         WeakReference wr = new WeakReference(r1);             
        final LevakandRestService r =(LevakandRestService)wr.get();
        r.RequestUBalance(balance);        
        final Progress p = new Progress(Globals.Loading, r);
        p.showPacked(BorderLayout.CENTER, false);
        p.setDisposeOnCompletion(true);
        r.addResponseListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {                              
                    p.dispose();                                      
                    Dialog.show(Globals.Info, "Balance:" +balance.getBalance(),Globals.OK, "");
            }
        });
        NetworkManager.getInstance().addToQueueAndWait(r);
        r1=null;                    
    balance1 = null;    
    System.gc();
    return val;
}
4

1 回答 1

0

您不需要调用 System.gc() 并且上面的代码不会编译,因为您将 null 分配给最终变量。

除非您保留对它们的引用,否则 ConnectionRequests 会被无缝收集,就这么简单。J2ME 的 WTK 2.5.2 有一个内存监视器,它允许您查看分配堆栈,对于 Codename One,您可以使用 NetBeans 分析器来监视内存分配并跟踪泄漏到它们产生的位置。

于 2012-08-09T16:29:01.323 回答