我有一个静态代码块:
public class MyClass {
static {
String s = "src/test/resources/dfdf.properties";
Resource r = new FileSystemResource(s);
Properties props = new Properties();
try {
props.load(r.getInputStream());
accessToken = props.getProperty("password");
locationToken = props.getProperty("username");
} catch (IOException e) {
LOG.error("We have an error for reading the access and location tokens for Brink web-service config");
}
}
}如果我正确理解它,即使我们有并发环境,静态代码块也只能运行一次。是对的吗?
发布于 2020-06-10 09:06:45
是的,这段代码是第一次执行的,当类装入器添加的类时,您知道,在类加载之后,所有方法信息和相关信息都将存储在JVM中的方法区域中,并且这些信息将由程序中的所有线程共享。因此,其他线程只访问该区域中的方法定义、字段、常量池信息,不再执行这样的静态块。
https://stackoverflow.com/questions/62298939
复制相似问题