javajava-8java-17

How to dynamically read an environment variable changes in java program?


I am having a small code snippet that read an environment variable within a for loop and prints its value and then sleep for sometime in java. It prints correctly, then I change the value of the environment variable from the terminal while my program is running & however it doesn't print the updated value .

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

what changes should i make so that my program read latest updated value for the environment variable ?


Solution

  • what changes should i make so that my program read latest updated value for the environment variable ?

    None (see below).

    The question seems to spring from a misunderstanding of the environment and environment variables. In particular, it supposes that there is a reason to expect that Java would observe environment changes made externally to it. There is not.

    Every process has its own environment, initialized at process creation as a copy of its parent process's environment. No process can modify a different process's environment -- neither that of an existing child process nor that of its parent process, much less that of less closely related processes. Your program is not reporting on changes to its environment because its environment is not changing. If its API_KEY variable were changing then your program would see it.

    There is no workaround for what I think you want to do short of devising a different mechanism than environment variables for communicating with the already-running Java program.