【问题标题】:Avoid infite loop while message consume按摩消耗时避免无限循环
【发布时间】:2021-09-21 14:01:24
【问题描述】:

您好,我有以下代码:

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(shouldRun)
  • 您是否有可能在这里对某些监视器使用等待/通知内置方法?经典方式
  • @marstran :根据您的建议,我已经更新了问题。你的意思是这样的。你可以看看并回复..
  • @AlexanderAlexandrov :是的,我可以使用睡眠等待等。
  • 如果你的代码是正确的,那么 SonarCube 就是错误的。重新配置(或完全放弃)SonarCube。

标签: java multithreading infinite-loop


【解决方案1】:

不使用 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 来停止胎面的处理。声纳配置是正确的,它会一直抱怨这样的错误。您需要更改代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2019-05-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    相关资源
    最近更新 更多