在用reduce时出现一个问题,在这上面耗费了好些时间,一直以为是业务逻辑方面的问题,不曾想是技术上的问题:reduce中迭代器返回对象的问题。写此blog以纪念在解决这个问题时的怂……囧
先看这个reduce的实例:
public static class sellerInfoReduce extends MapReduceBase implements Reducer<Text, Promotion, Text, Promotion> {
private static final Set<Promotion> set = new HashSet<Promotion>();
private static final Text k = new Text();
@Override
public void reduce(Text key, Iterator<Promotion> values,
OutputCollector<Text, Promotion> output, Reporter reporter)
throws IOException {
set.clear();
Promotion obj = null;
Promotion sellerPromotion = null;
int count = 0;//记录while循环次数
while(values.hasNext()) {
count++;
obj = values.next();
if(obj.isNull()) {
sellerPromotion = obj;//how asshole!
System.out.println("threadId="+Thread.currentThread().getId()+" count="+count+" 1:sellerPromotion===="+sellerPromotion);
}
else {
set.add(obj);
if(sellerPromotion != null) {
System.out.println("threadId="+Thread.currentThread().getId()+" count="+count+" 2:sellerPromotion===="+sellerPromotion);
System.out.println("threadId="+Thread.currentThread().getId()+" count="+count+" 2:obj===="+obj);
}
}
}
}
}
忽略业务,先看一个reduce执行的结果
threadId=1 count=1 1:sellerPromotion====object.Promotion@5a4
threadId=1 count=2 2:sellerPromotion====object.Promotion@13691399
threadId=1 count=2 2:obj====object.Promotion@13691399
threadId=1 count=3 2:sellerPromotion====object.Promotion@136912c0
threadId=1 count=3 2:obj====object.Promotion@136912c0
threadId=1 count=4 2:sellerPromotion====object.Promotion@136912bb
threadId=1 count=4 1:obj====object.Promotion@136912bb
开始是由于业务的问题发现最终结果与预期不符,在代码中打日志调试发现了这个问题。reduce方法的javadoc中已经说明了会出现的问题:
引用
The framework calls this method for each <key, (list of values)> pair in the grouped inputs. Output values must be of the same type as input values. Input keys must not be altered. The framework will reuse the key and value objects that are passed into the reduce, therefore the application should clone the objects they want to keep a copy of.
也就是说虽然reduce方法会反复执行多次,但key和value相关的对象只有两个,reduce会反复重用这两个对象。所以如果要保存key或者value的结果,只能将其中的值取出另存或者重新clone一个对象,而不能直接赋引用。因为引用从始至终都是指向同一个对象,会影响最终结果。
下面说一下在本例中犯二的地方。从结果可以看出,虽然sellerPromotion只被赋了一次引用,根据上面说的,直接打印对象(也即对象地址的标识)结果并不会改变,但是结果表示在每次while时,sellerPromotion的地址都会发生变化,这也是本例犯二所在。System.out.println(instance)会调用对象的toString()方法,而toString()方法的默认实现是:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
其中有变化的也即hashCode(),而我自定义对象恰恰重写了hashCode()方法,所以每次打印都会不一样。如果用默认的hashCode()方法,那打印出来的结果便会一致了。
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com