Memory leak when use newInsance() method

114 views Asked by At

I have the following method with the for loops. I'm concern about the memory leaking by doing that. My question: For every loop in for loops, Is that true that newInstance() method will allocate new memory block? If that so, should I create a VehicleImpl Instance before step into the for loop and try to set new values for this VehicleImpl Instance.

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

There are 1 answers

0
cecunami On BEST ANSWER

There is no leaking memory here. There is just a temporary reference variable that is created and destroyed in each iteration of the for loop. You can avoid that by declaring that variable before the for loop.