我有一个小代码片段,它在 for 循环中读取环境变量并打印其值,然后在 java 中休眠一段时间。它打印正确,然后我在程序运行时从终端更改环境变量的值,但它不会打印更新的值。
Step 1: export the environment variable
export API_KEY=tester
step 2: run the program
public class TestEnv {
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<1000;i++) {
// String apiKey = System.getenv("API_KEY");
String apiKey = System.getenv("API_KEY");
System.out.println("API_KEY value: " + apiKey);
Thread.sleep(1000);
}
}
}
output
API_KEY value: tester
API_KEY value: tester
API_KEY value: tester
step 3:
export API_KEY=bingo
however the program still print the value tester
我应该进行哪些更改,以便我的程序读取环境变量的最新更新值?
我应该进行哪些更改,以便我的程序读取环境变量的最新更新值?
没有。
这个问题似乎源于对环境和环境变量的误解。特别是,它假设有理由期望 Java 能够观察外部对其进行的环境更改。没有。
每个进程都有自己的环境,在进程创建时初始化为其父进程环境的副本。任何进程都不能修改不同进程的环境——无论是现有子进程的环境还是其父进程的环境,更不用说关系不太密切的进程的环境了。您的程序不会报告其环境的变化,因为它的环境没有变化。
除了设计一种与环境变量不同的机制来与已运行的 Java 程序进行通信之外,没有其他解决方法。