A bloody case caused by a list

In fact, the use of the bloody case is a bit of a headline party, just for Bo Jun's attention, and put a universal sentence for the New Year's Eve, come here, just read it.

We have a business system that has been running for several years, and it has been very stable. The front-end time system suddenly started to report memory overflow. After analyzing and positioning, it was found that the problem was with this code:
List<ModelBean> beaList = null;
for(int i=0; i<loop; i++) {
 beanList = service.getBeanList();
 businessProcess(beanList)
}


Well, a very simple piece of logic, query a list from the database, and then process the business logic.
There seems to be no problem! ?
Indeed, it runs very comfortably when the amount of data is small, but! When the magnitude of the data grows, the problem comes!
Analysis:
beanList returns 1000w data for the first time, starts to process business logic, and completes the processing. At this time, the beanList in memory is directly generated in the old age due to the excessive memory usage, and the second time it returns 1000w data from the database, the memory Insufficient, the GC starts to work, but it is found that the original beanList that was used for the first time still exists due to the reference outside the for block, and the memory cannot be recovered. The futile fullGC starts, and the result is out of memory.

The problem is analyzed, and the solution is very simple:
for(int i=0; i<loop; i++) {
 List<ModelBean> beanList = service.getBeanList();
 businessProcess(beanList)
}

Enclosing the life cycle of beanList in a for loop solves the problem.

Some people may say, is such a basic question worth writing an article about? In fact, it is not. The simplest problems are often the ones we most easily overlook. Solving problems is generally easy, but finding and analyzing problems is difficult. When I started learning effective java, I saw that the life cycle of a local variable is as close as possible to the end of its use cycle. The code has been written for a long time, and it has become more and more arbitrary. Over time, many basic requirements are forgotten. A wake-up call to yourself.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326270994&siteId=291194637