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

Java program continues to run (in background) even after last statement in main

背景

我有一个简单的 java 程序,它从标准输入读取数据。我正在从 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/[ 之后的 finally 块中=15=]。此外,stdinReader.close(); 也属于 finally