0

I have a GUI application which needs to run silently in the background and keep collecting the information. It needs to display UI initially for entering the credentials and then occasionally for displaying the errors.

I understand that I cant run the GUI app as a service, so I thought of creating service just to launch the GUI application. So the first program is run as a service, which just starts the GUI application and then keeps listening for any information from the GUI app. Below is the code for the first application which launches the GUI application.

String path =   Paths.get("D:\\Dempapp.jar").toAbsolutePath().normalize().toString();
 String[] startOptions = new String[] {"javaw", "-jar", path};
    Process p = new ProcessBuilder(startOptions).start();

    Timer tempTimer = new Timer();
    tempTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println((new Date()).toString());
        }
    },new Date(),10*1000);

When I run this, the GUI application is launched but freezes at some point with 5-10 seconds, so the GUI is never launched. However, if I kill the first application which launched the GUI application, the GUI shows up immediately, and then continues to work as expected. And I haven't yet started running the first application as a service yet, I am still running it from command line.

So is there any better way to launch this GUI application from a windows service?

kiran
  • 2,280
  • 2
  • 23
  • 30
  • See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and (continue to) use a `ProcessBuilder` to create the process. – Andrew Thompson Apr 13 '20 at 10:31

1 Answers1

2

When you start a process from within a process you need to handle the process systemoutput. Since the output is buffered it will evenetuelly exeed the maximum and then your child process freezes.

 String path = Paths.get("D:\\Dempapp.jar").toAbsolutePath().normalize().toString();
 String[] startOptions = new String[] {"javaw", "-jar", path};
 Process p = new ProcessBuilder(startOptions).start();

  BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
  String line;
  while((line=br.readLine())!=null) {
     // DISCARD IT. 
  }

You may also discard it or handle it otherwise.

See also here: Java ProcessBuilder: Resultant Process Hangs

Marcinek
  • 2,144
  • 1
  • 19
  • 25
  • 1
    Thanks. It resolved the issue. I was under the impression that this piece was needed only if the output needs to be printed. I was wrong. – kiran Apr 13 '20 at 11:02