GetResourceAsStream returns null randomly and infrequently

I get a null pointer exception when using getResourceAsStream very rarely, like once for every 10,000 starts. It looks like a class

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 you can see here, the class is implemented as a singleton. The resource clearly exists and shows up most of the time, but I'm not sure why its failure from time to time seems very strange to me.

+4
source share
1 answer
  • This will help to find out what is null (propies? Value returned by getResourceAsStream?)
  • I assume that you are calling getInstance from multiple threads, and one of them gets a ConfigLoader that was not correctly initialized 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 so, 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 enumeration:

 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 this be a packaging problem because the resource was not included in your jar?

+3
source

Source: https://habr.com/ru/post/1500378/


All Articles