我遇到了一个奇怪的问题。我希望有人会找出原因。 代码:在新线程中使用Apache HttpClient,我不知道它是否运行完毕
public static void asyncSend(final RoomNotification notification, final int retryTimes) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
boolean finish = false;
try {
ObjectMapper mapper = new ObjectMapper();
String messageString = mapper.writeValueAsString(notification);
logger.info("json to send to Hipchat :{}", messageString);
#1 Content content = Request.Post("https://api.hipchat.com/v2/room/<hidden>/notification?auth_token=<hidden>")
.bodyString(messageString, ContentType.APPLICATION_JSON)
.execute().returnContent();
#2 logger.info("Hipchat return:{}", content.asString());
finish = true;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
#3 logger.info("send Hipchat {}:\n{}", finish ? "successfully" : "unsuccessfully", notification.message);
if (finish) {
return;
}
//如果失败,且还有重试次数就重新发送
if (retryTimes > 0) {
logger.info("retry sending Hipchat, retry times remain:{}\nmessage:{}", retryTimes, notification.getMessage());
try {
Thread.sleep(10000); //重试前暂停10秒
} catch (InterruptedException e) {
e.printStackTrace();
}
asyncSend(notification, retryTimes - 1);
} else {
logger.info("no retry times remain, finally send Hipchat unsuccessfully.\nmessage:{}", notification.getMessage());
}
}
}
});
thread.start();
}
的问题是,有时在既不#2也不#3的线将被运行。这是否意味着线程无一例外地崩溃,或者#1线路从未完成运行? 第1行的代码是Apache Httpcomponents的参考。
我浅析浅析日志刚才下面的输出显示:
[[email protected] ~]$ grep "json to send to Hipchat" tomcat-mixi/logs/catalina.out | wc -l
216
[[email protected] ~]$ grep "send Hipchat successfully" tomcat-mixi/logs/catalina.out | wc -l
197
[[email protected] ~]$ grep "send Hipchat unsuccessfully" tomcat-mixi/logs/catalina.out | wc -l
14
所以这个问题发生5(216-197-14)次。 希望有人能帮助我!
谢谢@Thomas。这个答案适用于我! – 2014-11-13 03:25:35
我用jstack,发现有些线程很长一段时间都停留在AppacheHttpClient的方法中。看起来他们正在等待被唤醒。我认为这是AppacheHttpClient的一个缺陷。最后,我放弃了这个机制,并使用nodejs来实现这一点。 – 2014-11-13 03:40:19