我想发送电子邮件给多个(500,1000,2000)用户。
我用ExecutorService做了这件事。
但是现在我想从总记录中收集成功发送的电子邮件数量和失败邮件的数量。
我实施了如下措施:
int startValue=0;
int endValue=0;
List userEmailList = getListFromDB();
ExecutorService e = Executors.newFixedThreadPool(10);
Collection c = new ArrayList();
while (someflag)
{
// in MyTask class I am sending email to users.
c.add(new MyTask(startValue, endValue,userEmailList));
}
e.invokeAll(c); //Here I am calling invokeall .
pool.shutdown();
public class MyTask implements Callable<String> {
MyTask(startValue, endValue,userEmailList){
}
public String call(){
//e.g. batch 1 will have - startValue => endValue = 0 -100
//e.g. batch 2 will have - startValue => endValue = 101 -199
//e.g. batch 3 will have - startValue => endValue = 200 -299
//e.g. batch 4 will have - startValue => endValue = 300 -399
//e.g. batch 5 will have - startValue => endValue = 400 - 499
for(int i=startValue;i<endValue;i++){
sendEmailToUser(userEmailList.get(i)){
}
}}
但是future.get()返回我完成的任务数量。因此,从上面的代码,它将返回我的5任务。
但我希望输出没有失败的电子邮件和成功发送的电子邮件数量。
例如,如果有500个电子邮件用户,如果有20个失败,那么输出应该是480成功和20个失败。
但是有了上面的代码,我就没有任务了。IE5任务
有人能告诉我如何从所有并发任务(而不是完成任务的数量)中获得反馈吗?
发布于 2012-10-29 15:50:53
您的MyTask返回一个String (实现Callable<String>),这在您的情况下没有多大意义。您可以自由地返回任何您想要的类型。不幸的是,您需要一些简单的POJO来包含结果,例如:
public class Result {
private final int successCount;
private final int failureCount;
public Result(int successCount, int failureCount) {
this.successCount = successCount;
this.failureCount = failureCount;
}
}并在给定批处理完成后返回它(实现Callable<Result>)。当然,您的MyTask将必须跟踪有多少电子邮件失败,并返回正确的值包装在Result。
但是,我看到了几种可以改进代码的方法。首先,不要将startValue, endValue范围传递给MyTask,只需使用userEmailList.subList(startValue, endValue) -这将大大简化您的代码
new MyTask(userEmailList.subList(startValue, endValue));
//...
public class MyTask implements Callable<Result> {
MyTask(userEmailList){
}
public Result call(){
for(email: userEmailList) {
sendEmailToUser(email);
//collect results here
}
return new Result(...);
}
}另一方面,创建只发送一封电子邮件的MyTask没有什么错。与在给定批处理中聚合计数不同,您只需检查一项任务(一封电子邮件)的结果--“无”或“异常”(或单个Boolean)。这要容易得多,也不应该慢。
发布于 2012-10-29 15:48:44
我可以看到,call方法被声明为返回字符串,但代码不返回任何内容(可能是不完整的代码段)。从您的声明中,我了解到您正在返回任务是否完成以及邮件是否已发送。根据邮件是否已成功发送,您可以使sendEmailToUser返回失败的成功,并使用Future.get获得结果。
https://stackoverflow.com/questions/13124905
复制相似问题