Java problem records - secondary judge and state in the update cycle

Java problem records - secondary judge and state in the update cycle

Abstract: This paper records the problems that may occur during cyclic operation.

To reproduce the problem

When using the loop structure, if a timed task, or code that calls the cycle structure several times, could lead to some objects it will be recycled many times.

For example, if there is a checkout of the code will be executed once every five minutes:

. 1 @Scheduled (the cron = "* * * 0 0/5?" )
 2  @Async
 . 3  public  void handle () {
 . 4      List <the Customer> = customerDao.listCustomerByStatus List (0); // [ "zhangsan", "Lisi "] 
. 5      for (Customer the Customer: List) {
 . 6          customerDao.updateCustomerStatus (customer.getName (),. 1); // represents checkout is
 7          // checkout codes 
. 8          customerDao.updateCustomerStatus (customer.getName (), 2); / / indicates completion of settlement 
9      }
 10 }

Assume checkout code execution time is too long, more than five minutes.

The first time the trigger timing task, the query to the state of 0 customers have ZhangSan and LiSi, enter the loop code block, the status change will ZhangSan 1 and executes a transaction code.

Since the checkout code execution for more than five minutes, so the timing of when the next time the task is triggered, ZhangSan also executes a transaction code, then the state LiSi or 0.

When the second trigger timing tasks, query the status of the customer has LiSi 0, code block into the circulation, into the state 1 and LiSi executes a transaction code.

When the scheduled task first triggered after executing ZhangSan checkout code cycle to the next customer LiSi checkout code, and regular tasks at this time in the second trigger has been executed LiSi checkout code, which will lead to customer LiSi checkout the code is repeated twice.

Solution

The first approach is to be found in the data cycle again, the state changed to 1, and then perform a loop for each customer checkout.

The second option is to re-determine the state, each time the loop executes a transaction code have to re-check what the status of the customer, but this approach requires every query the database.

Problem Description

When using loop code should pay attention to whether there is a state change, if any, you need to consider whether there is a repeated process of risks.

Guess you like

Origin www.cnblogs.com/shamao/p/12067067.html