Search code examples
javaandroidmultithreadingprocessadb

Java thread not running to completion, why?


I have a Runnable that transfers data(a few hundred files) from an android device to a PC by doing the following in its run method

  1. Creates a process and executes a command using Runtime.exec(CMD)
  2. The CMD is a command that transfers data from a device to the PC that runs this thread. (This is an adb pull command for android )

I have a main program that creates a Thread and starts this runnable. The runnable starts running and it executes the "adb pull" command and starts transferring the data, BUT it seems to pause soon after before it completes the full transfer. IF I force quit the main program, the transfer runs to completion.

Also had I executed the command from the main program itself without using another thread, I face no issues.

Why am I facing this issue?


Solution

  • You need to consume the output of the command.

    This question shows how to consume the output in shell scripts rather than your code: Java ProcessBuilder: Resultant Process Hangs .

    If you want to consume the output in your Java code, basically you'll read from InputStream provided by Process.InputStream.

       Process process = Runtime.exec(CMD);
       InputStream in = process.getInputStream();
       // Repeatedly read from the input stream until eof.
    

    This blocks until the other process is complete. If you wanted concurrency, you could read the output in a another thread.