Prasanna
Prasanna

Reputation: 3771

Handling JVM thrown exceptions during initialization

I have one java process starting another java process with JMX support enabled in the following way

java -Dcom.sun.management.jmxremote.port=8088 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -jar app.jar

My problem is if the port 8088 is in use, the jvm of spawned process will throw BindException and the JVM will exit normally. There is no way for me to report back to the process that spawned process did not start because of bind exception. How can I catch/handle the BindException thrown by JVM so that the spawned process can do a System.exit(VALID_ERROR_CODE)? This exception happens even before any control is passed to the user code, so I guess it wouldn't be possible to handle it in the user code.

Any idea as how to handle this use case?

Upvotes: 0

Views: 296

Answers (2)

64BitBob
64BitBob

Reputation: 3110

Is it feasible to check if the port is open before launching the child process? i.e. Try listening on the port and if your socket fails, you know that port is unavailable. The advantage to this solution is that you could generate a new port number and keep testing until you find an open port. Once you have a valid port, you can modify the call to launch the child JVM with the available port.

Upvotes: 0

alexsmail
alexsmail

Reputation: 5813

You should redirect stderr (and maybe also stdout) from your subprocess to the parent process or to System.err (System.out). Look on https://stackoverflow.com/a/1570269/1137529 for more details.

Upvotes: 2

Related Questions