简体   繁体   English

getResourceAsStream随机且不经常返回null

[英]getResourceAsStream returns null randomly and infrequently

I'm getting a null pointer exception when using getResourceAsStream very rarely like once for every 10000 runs. 我使用getResourceAsStream很少得到一个空指针异常,很少像每10000次运行一次。 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?) 这将有助于找出什么是null(propies?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 我的猜测是你从几个线程调用getInstance ,其中一个得到一个未正确初始化的ConfigLoader,因为你的单例不是线程安全的

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: 所以我首先要确认日志记录,当它失败时,这是因为propies为null,如果是这样,那么使单例线程安全,例如:

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? 或者,如果getResourceAsStream("/config.properties")返回null,那么由于资源没有包含在jar中,它是否会成为打包问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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