方法中列出的赋值是否会导致内存泄漏

时间:2016-01-16 17:41:49

标签: java memory-leaks

我想知道populateResponse()中可能重置金额是否会导致内存泄漏。此类意图用于处理Web服务请求。我的理解是在(i)创建的BigDecimal如果对padAmount()的调用返回一个新的BigDecimal并且在方法执行后将超出范围并将被标记为GC,则将被视为本地对象实例。 这是对的吗?

public SampleResponse processRequest(SampleRequest request){
        BigDecimal amount = new BigDecimal("12.3000"); // this will pad
        //BigDecimal amount = new BigDecimal("12.35"); // this will not pad, but 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 an amount
        Integer newScale = 2;
        BigDecimal paddedAmount = this.padAmt(newScale, finalAmount);
        response.setRespAmount(paddedAmount); //(ii) Possible reset of amount. Will this cause a memory leak if the paddedAmount has a 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 with zeros");
               return new BigDecimal(amtWoTrailingZeros).setScale(newScale);
            }else {
                System.out.println("No Need to pad amount with 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 is 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());
    }

1 个答案:

答案 0 :(得分:1)

如果你认为存在内存泄漏,你应该能够通过在某个循环中运行有问题的代码来触发OutOfMemoryError。但似乎这里没有泄漏!

来自您的代码中的此评论

  

如果paddedAmount有新的内存地址会导致内存泄漏吗?

似乎你对内存泄漏是非常困惑的:当应用程序的内存不再需要时,程序仍在使用时会发生泄漏。为了有内存泄漏,需要有一个长生命对象(应用程序定义或语言定义,如Class,所以要注意static字段!)与重量级字段(字节数组,本机内存,无论如何)或存储对象集合但未正确清除的字段。