How to externally call a java program that is - and - has been running for some time

StackOverflow https://stackoverflow.com/questions/22150392

  •  19-10-2022
  •  | 
  •  

Pregunta

The time issue doesn't really matter. But i'm wondering how to make some external calls to a java program that is already running.

A simple example: An infinite loop that does some processing on files.

If i had such a program described above, how could i write a shell/perl/python/etc script that would allow me to stop, start, pause, the java program?

¿Fue útil?

Solución

This is not really easy but you can use the RMI to access controlling class that expose an API to control your application.

http://docs.oracle.com/javase/tutorial/rmi/index.html

Otros consejos

Unless your Java application explicitly enables to access it externally (e.g. from RMI, SOAP/REST-WebService, MQ, ...) there is no direct way to access your Java program.

The simplest (but certainly not the best) solution is to use the File System as in between. Your shell script creates a file which is picked up by the Java application. E.g create a file pause; if the app sees this file exists it will delete it and pause. Stopping the app is simply killing the process.

The simplest way is to write a script that starts the program on 'start', and send a SIGTERM signal to the the Java process on 'stop'. Your code can handle the signal accordingly for clean shutdown.

This will be sufficient if it's just a start/stop script scenario. For more advanced behaviour, the other answers mention other alternatives which require networking.

A way could be that the main program, in an ad-hoc thread control, listen in a TCP socket for external commands, while the control script should write to that socket.

There are many ways a program can interact with the outside world. The commonest way nowadays in the Java world is to make your program a TCP server.

One common way is to use an embedded HTTP server such as Jetty. Your program would start Jetty in its own thread before going into its task. You can write servlets that interact with your program. You can use a Web browser to talk to it, or an HTTP client tool like cURL, or an HTTP client library for whatever language you like.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top