hadoop中迭代器的对象重用问题

        在用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()方法,那打印出来的结果便会一致了。

猜你喜欢

转载自paddy-w.iteye.com/blog/1514595