简体   繁体   中英

getResourceAsStream returns null randomly and infrequently

I'm getting a null pointer exception when using getResourceAsStream very rarely like once for every 10000 runs. This is how the class looks like

public class ConfigLoader{
  private Properties propies;
  private static ConfigLoader cl = null;
  private ConfigLoader(){
        propies = new Properties;
  }
  public static ConfigLoader getInstance(){
    if(cl == null){
          cl = new ConfigLoader();
    }
  }

  public boolean Load(){
   try{
         propies.load(this.getClass().getResourceAsStream("/config.properties"));          
   }
   catch(NullPointerException e){
         System.out.println("File Does Not Exist");
         return false;
   }
   return true;
   }
}

As can be seen here, the class is implemented as a singleton. The resource clearly exists and is detected most of the time but I'm not sure why its failing once in a while which seems really strange to me.

  1. It would help to find out what is null (propies? the value returned by getResourceAsStream?)
  2. My guess is that you call getInstance from several threads and one of them gets a ConfigLoader that has not been properly initialised because your singleton is not thread safe

So I would first confirm with logging that when it fails, it is because propies is null, and if it is the case, make the singleton thread safe, for example:

private static final ConfigLoader cl = new ConfigLoader;
public static ConfigLoader getInstance() { return cl; }

or even better use an enum:

public enum ConfigLoader{
  INSTANCE;
  private Properties propies;
  private ConfigLoader(){
    propies = new Properties;
  }

  public static ConfigLoader getInstance(){ return INSTANCE; }

  public boolean Load(){
   try{
         propies.load(this.getClass().getResourceAsStream("/config.properties"));          
   }
   catch(NullPointerException e){
         System.out.println("File Does Not Exist");
         return false;
   }
   return true;
   }
}

Alternatively, if getResourceAsStream("/config.properties") returns null, could it be a packaging issue due to the resource not having been included in your jar?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM