简体   繁体   中英

Java program hangs when running a batch file

I am using below the code to generate a report from input data. When there is only a little data, the below code works fine. But when the amount of data become greater, then my program hangs and have to kill the process using task manager to close the application.

public void launchReport() {

    if( selectionRulesRespected ) {

        final Process p;

        final String userNameParLine = getUserNameParLine();
        final String injParLine = getFilterByFieldParLine();

        writeTmpParFile(tmpParFilePath, new String[]{userNameParLine, injParLine});

        try {
            final ProcessBuilder builder;
            if( exporting != null && "TRUE".equals(exporting.toUpperCase()) ) {
                builder = new ProcessBuilder("cmd", "/c", batFilePath, reportName, tmpParFilePath, exportFilePath);
            }
            else {
                builder = new ProcessBuilder("cmd", "/c", batFilePath, reportName, tmpParFilePath);
            }
            //builder.directory( new File(viewerDirPath));
            p = builder.start();
            p.waitFor();
        } catch (final IOException e) {
            PlanonMessageDialog.showErrorDialog(ioError);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }

    } else {
        PlanonMessageDialog.showErrorDialog(wrongItem);
    }
}

The application hangs because this method waits for the process to be completed. What are the options that I can use for this?

Your java code uses p.waitFor() to wait until the process terminated. But the process writes to stdout/stderr, the buffer is full and thus Windows stops it from executing further - instead it waits for the buffer to be emtpied. Both processes wait for each other - that's a classic deadlock.

To prevent this, replace p.waitFor() with a loop that checks whether the process has exited. If not, read from both stdout and stderr.

See also https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Process.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM