Search code examples
javamultithreadinginfinite-loop

Avoid infite loop while message consume


Hi I have the following code :

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();
            }
        }
    }       
}

This is throwing a sonar issue with infinite loop. But this consume() is deliberately kept in infinite loop to continue mesage consumption. How to avoid the infinite loop error in this scenario ?

UPDATE:

Thinking of keeping the condition as below, but will this server my purpose of the infinite loop ?

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();
    }
}

Solution

  • insetead of using while (true) , you should check if the thread has been stopped or paused.

    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.
           
         }
       }
     }
    

    So, you can use the flag isStopped to stop the processing of the tread. Sonar configuration is correct, it will keep complaining about such error. You need to change code.