My application makes hundred new Connection requests a day and parses json responce. But I've realized that it doesn't free the memory after each request.Though using system.gc() it stores the ConnectionRequest instance and instance of my class for parsing json responce. I guess at the end it causes system out of memory error.
here is some code:
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;
}
I've tried using WeakReference but it doesn't helped.
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;
}
You don't need to call System.gc() and the code above doesn't compile since you are assigning null to a final variable.
ConnectionRequests get collected seamlessly unless you keep a reference to them, its as simple as that. J2ME's WTK 2.5.2 has a memory monitor which allows you to see the allocation stack and for Codename One you can use the NetBeans profiler to monitor memory allocations and trace leaks back to the place where they originated.