java - getResourceAsStream returns null randomly and infrequently -
i'm getting null pointer exception when using getresourceasstream once every 10000 runs. how 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 not exist"); return false; } return true; } }
as can seen here, class implemented singleton. resource exists , detected of time i'm not sure why failing once in while seems strange me.
- it find out null (propies? value returned getresourceasstream?)
- my guess call
getinstance
several threads , 1 of them gets configloader has not been initialised because singleton not thread safe
so first confirm logging when fails, because propies
null, , if case, make singleton thread safe, example:
private static final configloader cl = new configloader; public static configloader getinstance() { return cl; }
or better use 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 not exist"); return false; } return true; } }
alternatively, if getresourceasstream("/config.properties")
returns null, packaging issue due resource not having been included in jar?
Comments
Post a Comment