Skip to content
Advertisement

Singleton writes a field in unsynchronized manner

I am getting : Singleton class writes to a field in an unsynchronized manner at 4-5 places in Springboot code while scanning through SonarQube. Now, I am trying to understand how can I make this warning go away? Is there a general fix for this error

One example is below :

public class NewProvProcess {
    
    @Autowired
    DataExecutor dataexecutor;
    
    String flag = "N";
    
    public void dbFetchNewProvRecords() {
        
    do {
        try {
            Thread.sleep(180000);
            flag = dataexecutor.fetchNDBRunStatus();
            LOGGER.info("The Flag value is {}, checking again after 3 minute ", flag);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
            
        }while(("N").equals(flag));
        
    }
}

enter image description here

Advertisement

Answer

  1. never ever expose a mutable field directly, least of all if there is any chance a different thread might need to access it – make it private.
  2. synchronize all access to the field.

In the simplest case, something like this might do:

public class NewProvProcess {
    
    @Autowired
    DataExecutor dataexecutor;
    
    private String flag = "N";
    
    public void dbFetchNewProvRecords() {
        
        do {
            try {
                Thread.sleep(180000);
                synchronized(this) {
                    flag = dataexecutor.fetchNDBRunStatus();
                    LOGGER.info("The Flag value is {}, checking again after 3 minute ", flag);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            
        }while(("N").equals(flag));
        
    }

    synchronized String getFlag() {
        return this.flag;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement