Search code examples
javaprocessbuilder

Does ProcessBuilder() take some time to complete?


Does ProcessBuilder() take some time to complete? For example, some key is already defined for the OS you are using. Is it possible that when the second line executes the previous step isn't yet completed? (the second line will be using old key)

new ProcessBuilder().command("cmd.exe", "/c", "setx key abcd").start();
util.encode(); // it uses a `key` defined in previous line

Solution

  • It definitely takes some time (whatever time your command takes). The start method returns a Process, which you can wait for:

    var process = ProcessBuilder().command("cmd.exe", "/c", "setx key abcd").start();
    try {
        process.waitFor();
    } catch(InterruptedException e) {
        // Handle exception
    }
    util.encode();
    

    EDIT: in addition it is not clear that this will work the way you think it will. The system environment variable that you create may not be set for old/running processes such as your own; quite possibly it applies only to new ones. You'll notice soon enough, but if it doesn't work even with wait that may be the reason.