消费消息时避免无限循环

Avoid infite loop while message consume

您好,我有以下代码:

public abstract class MyConsumer<T extends IMessage, S extends ISubscriptionEnum>
    implements IBatchConsumer<T> {

    @Override
    public void run() {   
        
        while (true) {
            if(active){
                try{
                    // some condition
                    consume();
                }catch (Exception e) {
                    Thread.currentThread().interrupt();
                }
            }
            
            try {
                Thread.sleep(20000);
            } catch (Exception e) {
                LOGGER.error("Sleep was interrupted: " + e);
                Thread.currentThread().interrupt();
            }
        }
    }       
}

这是一个无限循环的声纳问题。但是这个consume()故意一直在死循环中继续消费消息。在这种情况下如何避免无限循环错误?

更新:

考虑保持如下条件,但是这个服务器会是我无限循环的目的吗?

while(active){
    try{
        consume();
    }catch(Exception e){
        Thread.currentThread().interrupt();
    }
    try {
        Thread.sleep(20000);
    } catch (Exception e) {
        LOGGER.error("Sleep was interrupted: " + e);
        Thread.currentThread().interrupt();
    }
}

不使用 while (true) ,您应该检查线程是否已停止或暂停。

private volatile boolean isStopped = false;

 public void run(){
   while(!isStopped ){
      try{
     // keep doing your logic
     }catch(){
       isStopped = true; // do this only if you want to stop. 
       Thread.currentThread().interrupt();// This line does not ensure thread to stop.
       
     }
   }
 }

因此,您可以使用标志 isStopped 来停止胎面的处理。 Sonar配置正确,会一直报这样的错误。您需要更改代码。