即使在 main 中的最后一条语句之后,Java 程序仍继续运行(在后台)

标签 java linux bash background-process

背景

我有一个简单的java程序,它从std输入读取数据。我正在从 bash 脚本 executer.sh

执行它
python2 readLines.py | tee logfile |  java MsgReader

readLines.py 从文件中逐行读取数据并将其扔到标准输出上

MsgReader.java

import kafka.javaapi.producer.Producer;

public void process() {
    String msg = ""; 
    BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in)

    Producer producer = new Producer();//it takes config file as parameter which is not related to the question here

    try {
         while ((msg = stdinReader.readLine()) != null) {
              producer.send(message);
         }   
         stdinReader.close();
     } catch (IOException|FailedToSendMessageException e) {
            System.out.println("Send message failed!");
            e.printStackTrace();
     }   
}   

public static void main(String args[]) throws JSONException,IOException {
    try{
        Date now = new Date();
        System.out.println("Start : " + now);
        process();// Continuously reads logs
        now = new Date();
        System.out.println("After : " + now);
    } catch(Exception e){ 
        e.printStackTrace();
        return;
    }   
}   

执行

./executer.sh & :在后台执行

问题

读取所有行后,readLines.py 结束,但 executer.shMsgReader.java 仍在执行,经 ps 命令验证。语句System.out.println("After : "+ now); os记录在日志文件中,表明程序已经到达main函数中的最后一条语句。

如何优雅地终止java程序和bash脚本。

我不想在此处添加System.exit()

平台

CentOS 版本 6.7(最终版)

java 1.7.0_95

python 2.7.6

最佳答案

您没有关闭 Producer。来自 KafkaProducer 的 Javadoc(Producer 的实现):

The producer consists of a pool of buffer space that holds records that haven't yet been transmitted to the server as well as a background I/O thread that is responsible for turning these records into requests and transmitting them to the cluster. Failure to close the producer after use will leak these resources.

后台线程仍在运行,并且会阻止进程结束,直到您关闭 Producer,最好是在 try/catch 之后的 finally block 中。另外,stdinReader.close(); 也属于 finally

关于即使在 main 中的最后一条语句之后,Java 程序仍继续运行(在后台),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939382/

相关文章:

java - 绘制圆圈内刻的字符串

linux - 如何组合两个不同的linux命令?

php - Apache 内存错误

Python – time.time() 与 bash 时间

linux - sed - 在其他文本之后插入文本

java - 当应用程序处于后台时,将数据从 BroadcastReceiver 发送到 Activity

java - 如何在Broadleaf中实现自己的ProductImpl?

java - 从 recyclerview 中的 editText 进行搜索,我使用改造从 API 获取项目

linux - 文件编辑-命令行 unix

arrays - 如何在 Bash 中对数组进行切片