我正在使用static
块在我的名为properties file
App1
public class Configuration{
static {
System.out.println("static ");
PropertyConfigurator.configure("./TwitterLog4j.properties");
log = Logger.getLogger(Configuration.class.getName());
configProp = new Properties();
try {
configProp.load(Configuration.class.getClassLoader().getResourceAsStream("TwitterConfig.properties"));
} catch (IOException e) {
throw new RuntimeException("TC100: Unable to load the connector configuration file. Configuration file is missing or is invalid.");
}
CONSUMER_KEY = configProp.getProperty("APPKEY");
CONSUMER_SECRET = configProp.getProperty("APPSECRET");
}
}
创建jar
App1
之后,我在App2
中使用它,我使用线程(Executors.newFixedThreadPool(10))
通过调用类{{的方法来运行App1
1}}(见下面的流程)。但我的静态块似乎只运行一次,即使我的ConnWrapper
完成,JVM是否会保持类加载?
App1
App1
答案 0 :(得分:1)
每个Jvm每个Classloader加载一次静态块。你的变量' configProp'是可以用来访问属性的类的静态变量,那么为什么需要多次加载它?
public class Configuration{
public static Properties configProp;
static{
reloadProperties();
}
public static void reloadProperties()
{
System.out.println("static ");
PropertyConfigurator.configure("./TwitterLog4j.properties");
log = Logger.getLogger(Configuration.class.getName());
configProp = new Properties();
try {
configProp.load(Configuration.class.getClassLoader().getResourceAsStream("TwitterConfig.properties"));
} catch (IOException e) {
throw new RuntimeException("TC100: Unable to load the connector configuration file. Configuration file is missing or is invalid.");
}
CONSUMER_KEY = configProp.getProperty("APPKEY");
CONSUMER_SECRET = configProp.getProperty("APPSECRET");
}
}
答案 1 :(得分:0)
这是静态块,根据java规范,它只加载一次多少次 我们调用该方法给出了相同的结果,因此这里不需要线程概念