Search code examples
powershellexecutionnonblocking

Powershell JAR executable occupies instance


I try to write a powershell script to run my Jar, which is just a simple hello world spring web mvc app using tomcat catalina servlet. The problem is that after I execute my Jar file, the powershell instance is occupied by the servlet. Which means I cant run a consecutive command -> open chrome on localhost:8080.

My current powershell script:

java -jar .\helloworld-0.0.1-SNAPSHOT.jar

# doesnt get executed due to the servlet occupation of the ps instance
Start-Process "chrome.exe" "http://localhost:8080" 

Is there a way to run the second comand within the same powershell instance, or would I need to open another ps insance? And if, how would I do that?


Solution

  • Executing Java code with java.exe runs the code synchronously, i.e. in a blocking fashion. Therefore, the Start-Process call isn't reached until after the server has shut down, which is obviously not the intent.

    You have two basic choices for making the call asynchronous:

    • Use Start-Process to run the command in a new window (Windows only):
    # Opens the server in a *new window* (Windows only)
    Start-Process java '-jar .\helloworld-0.0.1-SNAPSHOT.jar'
    
    • Use a background or thread job (Start-Job or Start-ThreadJob [v6+]), which runs the command in an invisible background process or thread that you can monitor and manage with the *-Job cmdlets:
    # Start the server in a background process.
    # In PowerShell [Core] 6+ you can use the lighter-weight Start-ThreadJob cmdlet.
    # Monitor it with the *-Job cmdlets, such as Receive-Job.
    $jb = Start-Job { java -jar .\helloworld-0.0.1-SNAPSHOT.jar }
    
    # Syntactically simpler PowerShell [Core] v6+ alternative:
    # (A postpositional & is the same as using Start-Job.
    # As of PowerShell 7.0, there is no operator for Start-ThreadJob.)
    $jb = java -jar .\helloworld-0.0.1-SNAPSHOT.jar &
    

    Use Receive-Job $jb to get the job's output and Stop-Job $jb to stop it (and thereby the server).