I have a method called getCustomerCount() which makes a database call to get the customer count based on the store like below.
public int getCustomerCount(String storeName) {
return repository.getCustomerCount(storeName);
}
I need to call the above method more than once from other methods so can I use an instance variable to set the customer count the very first time this method gets called and then reuse the variable instead of calling this method and making a database call every single time? Can I do something like this:
private int customerCount;
public int getCustomerCount(String storeName) {
int count = repository.getCustomerCount(storeName);
customerCount = count;
return count;
}
public void processCustomerData(String storeName) {
getCustomerCount(storeName);
// Based on customer count, add business logic
sendEmail(customerList);
}
public void sendEmail(List<Customers> customers) {
// get customer count and set email count to the number of customers in the system.
int emailCount = 0;
emailCount = customerCount;
}
Would this be an issue when multiple requests execute at the same time through a rest api? Are there any pros and cons of using instance variables like this? If there are better ways than using instance variables, please suggest. I need to execute the query for each request so singleton may not work for this case. Thank you.
getCustomerCount(). Second, your local variableemailCountis assigned but can't be used at all.private int customerCount;is not correct if this is@service, because spring-boot is singleton. you can keep the customerCount the place you call all this methods like:int customerCount = getCustomerCount();thenprocessCustomer(customerCount);