java - Would an assignment listed in the method cause a memory leak -
i know if possible resetting of amounts in populateresponse() can cause memory leak. class intent used process web service requests. understanding bigdecimal created @ (i) considered local object instance if call padamount() returns new bigdecimal , fall out of scope after method execution , marked gc. correct?
public sampleresponse processrequest(samplerequest request){ bigdecimal amount = new bigdecimal("12.3000"); // pad //bigdecimal amount = new bigdecimal("12.35"); // not pad, return passed in amount return this.populateresponse(amount); } public sampleresponse populateresponse(bigdecimal amount){ bigdecimal finalamount = new bigdecimal(amount.tostring(), new mathcontext(21)); sampleresponse response = new sampleresponse(); response.setrespamount(finalamount.setscale(6, roundingmode.up).striptrailingzeros()); //(i) setting amount integer newscale = 2; bigdecimal paddedamount = this.padamt(newscale, finalamount); response.setrespamount(paddedamount); //(ii) possible reset of amount. cause memory leak if paddedamount has new memory address return response; } public bigdecimal padamt(int newscale, bigdecimal amount) { string amtwotrailingzeros = amount.striptrailingzeros().toplainstring(); try { int decdigitsinamt = this.getnumberofdecimalplaces(amtwotrailingzeros); if(newscale > decdigitsinamt){ system.out.println("pad amount zeros"); return new bigdecimal(amtwotrailingzeros).setscale(newscale); }else { system.out.println("no need pad amount zeros"); return amount; } } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); system.out.println("exception caught here: " +e); return amount; } } public int getnumberofdecimalplaces(string decimalnumber) throws exception{ if (decimalnumber == null){ throw new exception("decimal number null"); } int index = decimalnumber.indexof("."); return index < 0 ? 0 : decimalnumber.length() - index - 1; } public static void main (string args[]){ requestprocessor rp = new requestprocessor(); samplerequest request = new samplerequest(); sampleresponse response = rp.processrequest(request); system.out.println("sample response amount: " +response.getrespamount().toplainstring()); }
if think there's memory leak, should able trigger outofmemoryerror running offending code in loop. seems there no leaks here!
from comment in code
will cause memory leak if
paddedamount
has new memory address?
it seems confused memory leaks are: there's leak when memory no more needed application still used program. in order have memory leak there needs long living object (either application-defined or language-defined, class, watch out static
fields!) either heavyweight field (a byte array, native memory, whatever) or field stores collection of objects , not cleared.
Comments
Post a Comment