以下代码应该将SMS发送到手机,并在操作成功时返回。如果Oerate在超过1分钟的时间内未成功,它应该中止操作并尝试发送另一个消息。该代码在测试环境中运行良好,但是当它在生产环境中实现时,似乎永远等待,直到操作成功地忽略60秒规则。如果有人可以在代码运行中发现任何问题,我希望您告诉我。
public synchronized String sendSms(MessageData messageData) {
class Task implements Callable<String> {
private MessageData messageData;
public Task(MessageData messageData) {
this.messageData = messageData;
}
@Override
public String call() throws Exception {
System.out.println("Sending MPT >>> " + "Number : " + messageData.getToAddress() + ", Message : "
+ messageData.getMessage());
SendSMS.send(messageData.getToAddress(), messageData.getMessage(),
Long.toString(messageData.getSyskey()));
//The real code that sends the message
//***
return "1";
}
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Task t = new Task(messageData);
Future<String> future = executor.submit(t);
try {
System.out.println("Started..");
future.get(60, TimeUnit.SECONDS);
executor.shutdown();
return "1";
} catch (TimeoutException e) {
future.cancel(true);
executor.shutdown();
return "-1";
} catch (InterruptedException e) {
executor.shutdown();
return "-1";
} catch (ExecutionException e) {
executor.shutdown();
return "-1";
}
}
此答案总结了评论中收集的信息。
OP使用API发送SMS消息。每个发送都将委派给正常短的线程,该线程实现为Callable
。不幸的是,API的send
功能可以无限期地阻止。
使用可以阻止的API时,存在三种常规情况:
- API"意识到" JVM并已实施,以便它可以响应Java中断异常并终止其操作。
- API不是Java-ware,而是具有超时选项,可以使其在指定的时间段后终止和返回。
- 阻止操作可能无限期阻止,并且在JVM中的动作不会中断。
使用标准Java技术容易处理前两种情况。
OP的问题是API似乎是第三种类型。在这种情况下,Callable
线程可以在60秒的超时后被主线程放弃,但是如果send()
API调用永远不会返回,则将永远不会终止线程。这将导致线程及其资源(网络端口,内存等)的永久泄漏,这将要求将应用程序重新启动监管以收回泄漏的资源。