Embarrassed, wrote an endless loop

Suddenly someone in the group said that there was a problem with the interface. Checking the log is that a third-party interface was called and the current limit was increased, and then the partner increased the current limit quota. The partner said that an interface has been called a million times. By checking the log, it was found that the program entered an endless loop.

Let's take a look at the infinite loop code:

boolean hasData = false;
do {
    
    
       // Boolean 表示下一页是否还有数据,合作方的接口会返回这个字段
       Pair<Boolean, List<OrderInfo>> orderListPair = getOrderList(dateTime, pageNumber, 500);
       if (Objects.nonNull(orderListPair)) {
    
    
           List<OrderInfo> orderInfoList = orderListPair.getRight();
           if (CollectionUtils.isNotEmpty(orderInfoList)) {
    
    
               // 处理 orderInfoList
           }
           if (Objects.nonNull(orderListPair.getLeft()) && orderListPair.getLeft()) {
    
    
               // 产生死循环的地方
               hasData = true;
           }
           pageNumber = pageNumber + 1;
       }
   } while (hasData);

The code above represents a time to acquire 500 data, when hasDatathe future is set to true, hasDatanever was true, and then whilebecame infinite loop, the test environment due to less amount of data and found no problem.

Just add a elsethe hasDataset falseto avoid the problem of infinite loop:

boolean hasData = false;
do {
    
    
       // Boolean 表示下一页是否还有数据,合作方的接口会返回这个字段
       Pair<Boolean, List<OrderInfo>> orderListPair = getOrderList(dateTime, pageNumber, 500);
       if (Objects.nonNull(orderListPair)) {
    
    
           List<OrderInfo> orderInfoList = orderListPair.getRight();
           if (CollectionUtils.isNotEmpty(orderInfoList)) {
    
    
               // 处理 orderInfoList
           }
           if (Objects.nonNull(orderListPair.getLeft()) && orderListPair.getLeft()) {
    
    
               hasData = true;
           } else {
    
    
               // 一定要设置成 false
               hasData = false;
           }
           pageNumber = pageNumber + 1;
       }
   } while (hasData);

So remember: if (expression)After the sentence to take account else {}of the circumstances, this test case not be able to test out, especially when the control loop, do not because of else {}lack of branch of the program to enter an infinite loop.

Guess you like

Origin blog.csdn.net/jiaobuchong/article/details/92436008