使用newInsance()方法时内存泄漏

时间:2017-11-29 09:06:43

标签: java memory memory-leaks builder jsprit

我使用for循环有以下方法。通过这样做,我担心内存泄漏。 我的问题:对于for循环中的每个循环,newInstance()方法是否会分配新的内存块是真的吗?如果是这样,我应该在进入for循环之前创建VehicleImpl实例并尝试为此VehicleImpl实例设置新值。

private List<VehicleImpl> setVehicles(JsonInput input) {
    List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();

    Break lunch = Break.Builder.newInstance("Lunch")
            //timewindow(start time, end time), so lunch timewindow(start, start + duration)
            .setTimeWindow(TimeWindow.newInstance(input.getLunch().getStart(),
                    input.getLunch().getStart() + input.getLunch().getDuration()))
            //Lunch has highest priority
            .setPriority(1)
            //Lunch takes serviceTime
            .setServiceTime(input.getLunch().getDuration())
            .build();

    VehicleType type =  VehicleTypeImpl.Builder.newInstance("vehicleType")
            .setCostPerDistance(input.getCosts().getCostPerMeter())
            .setCostPerTransportTime(input.getCosts().getCostPerTransportSecond())
            .setCostPerServiceTime(input.getCosts().getCostPerServiceTime())
            .build();

    for(int i = 0; i < input.getNoVehicles(); i++) {
                                                //Name vehicle by index
        VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle " + String.valueOf(i+1))
                //The first location - depot location is indexed as 0 in Matrices
                .setStartLocation(Location.newInstance(i))
                .setBreak(lunch)
                .setLatestArrival(input.getOperating())
                .setType(type)
                .build();
        vehicles.add(vehicle);
    }
    return vehicles;
}

1 个答案:

答案 0 :(得分:0)

这里没有泄漏的记忆。只有一个临时引用变量在for循环的每次迭代中创建和销毁。您可以通过在for循环之前声明该变量来避免这种情况。