I am facing of memory exception while running this code and the constraint is heap size. Can anyone suggest if there is a way to optimize this code further?
public class getCustomerList {
public static List <Customer> retrieve() throws ParseException {
List<Customer> customers = new ArrayList<Customer>();
for (int i = 0; i < 100000; i ) {
Customer customer = new Customer();
customer.setAge(new Integer(i));
customer.setBirthDate((new SimpleDateFormat("ddMMyyyy")).parse("01061986"));
customer.setName("Customer" new String((new Integer(i)).toString()));
customers.add(customer);
}
return customers;
}
}
CodePudding user response:
Few ideas that might help:
- Make age primitive, if it already is, provide the method an
int
, notInteger
.
customer.setAge(i);
- Move
SimpleDateFormat
outside the loop, currently you create 100000 same instances.
customer.setBirthDate(format.parse("01061986"));
- Do you really need 100000 same
Date
instances for every customer? If you don't, you can get away with setting the same date instance in every customer.
customer.setBirthDate(date);
- Current name creation is very inefficient, you create
Integer
object, then create string from it(and the integer is thrown away), then create copy of said string(and throw away the initial one). Just do:
customer.setName("Customer" i);
CodePudding user response:
The memory leak is caused by instantiating the class Customer
one-hundred thousand times. You aren't setting up your code in a way that makes the customer
variable eligible for garbage collection because the memory will remain in the heap until the for-loop has finished execution. You can experiment with setting customer
to null
after calling its methods, but this isn't a guaranteed fix and is strongly dependent on your code. An alternative would be to manually call garbage collection in your loop, but that will negatively affect the performance so it would hardly be considered optimization.
There are multiple other solutions to this, but you should probably answer the following question to get the most optimized solution: why are you even creating 100000 customers with almost the same information?