关于hadoop reduce阶段遍历Iterable的注意事项

之前有童鞋问到了这样一个问题:为什么我在 reduce 阶段遍历了一次 Iterable 之后,再次遍历的时候,数据都没了呢?可能有童鞋想当然的回答:Iterable 只能单向遍历一次,就这样简单的原因。。。事实果真如此吗?

还是用代码说话:

packagecom.test;
 
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
 
publicclass T {
 
    publicstatic void main(String[] args) {
 
        // 只要实现了Iterable接口的对象都可以使用for-each循环。
        // Iterable接口只由iterator方法构成,
        // iterator()方法是java.lang.Iterable接口,被Collection继承。
        /*public interface Iterable<T> {
            Iterator<T> iterator();
        }*/
        Iterable<String> iter = newIterable<String>() {
            publicIterator<String> iterator() {
                List<String> l = newArrayList<String>();
                l.add("aa");
                l.add("bb");
                l.add("cc");
                returnl.iterator();
            }
        };
        for(intcount : newint[] {1,2}){
            for(String item : iter) {
                System.out.println(item);
            }
            System.out.println("---------->> " + count + " END.");
        }
    }
}

结果当然是很正常的完整无误的打印了两遍  Iterable 的值。那究竟是什么原因导致了 reduce 阶段的  Iterable 只能被遍历一次呢?

我们先看一段测试代码:

测试数据:

a  3
a  4
b  50
b  60
a  70
b  8
a  9

importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
 
importorg.apache.hadoop.conf.Configuration;
importorg.apache.hadoop.fs.FileSystem;
importorg.apache.hadoop.fs.Path;
importorg.apache.hadoop.io.Text;
importorg.apache.hadoop.mapreduce.Job;
importorg.apache.hadoop.mapreduce.Mapper;
importorg.apache.hadoop.mapreduce.Reducer;
importorg.apache.hadoop.mapreduce.lib.input.FileInputFormat;
importorg.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
importorg.apache.hadoop.util.GenericOptionsParser;
 
publicclass TestIterable {
 
    publicstatic class M1 extendsMapper<Object, Text, Text, Text> {
        privateText oKey = newText();
        privateText oVal = newText();
        String[] lineArr;
 
        publicvoid map(Object key, Text value, Context context) throwsIOException, InterruptedException {
            lineArr = value.toString().split(" ");
            oKey.set(lineArr[0]);
            oVal.set(lineArr[1]);
            context.write(oKey, oVal);
        }
    }
 
    publicstatic class R1 extendsReducer<Text, Text, Text, Text> {
        List<String> valList = newArrayList<String>();
        List<Text> textList = newArrayList<Text>();
        String strAdd;
        publicvoid reduce(Text key, Iterable<Text> values, Context context) throwsIOException,
                InterruptedException {
            valList.clear();
            textList.clear();
            strAdd = "";
            for(Text val : values) {
                valList.add(val.toString());
                textList.add(val);
            }
             
            // 坑之 1 :为神马输出的全是最后一个值?why?
            for(Text text : textList){
                strAdd += text.toString() + ", ";
            }
            System.out.println(key.toString() + "\t"+ strAdd);
            System.out.println(".......................");
             
            // 我这样干呢?对了吗?
            strAdd = "";
            for(String val : valList){
                strAdd += val + ", ";
            }
            System.out.println(key.toString() + "\t"+ strAdd);
            System.out.println("----------------------");
             
            // 坑之 2 :第二次遍历的时候为什么得到的都是空?why?
            valList.clear();
            strAdd = "";
            for(Text val : values) {
                valList.add(val.toString());
            }
            for(String val : valList){
                strAdd += val + ", ";
            }
            System.out.println(key.toString() + "\t"+ strAdd);
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
        }
    }
 
    publicstatic void main(String[] args) throwsException {
        Configuration conf = newConfiguration();
        conf.set("mapred.job.queue.name","regular");
        String[] otherArgs = newGenericOptionsParser(conf, args).getRemainingArgs();
        if(otherArgs.length != 2) {
            System.err.println("Usage: wordcount <in> <out>");
            System.exit(2);
        }
        System.out.println("------------------------");
        Job job = newJob(conf, "TestIterable");
        job.setJarByClass(TestIterable.class);
        job.setMapperClass(M1.class);
        job.setReducerClass(R1.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        // 输入输出路径
        FileInputFormat.addInputPath(job,newPath(otherArgs[0]));
        FileSystem.get(conf).delete(newPath(otherArgs[1]),true);
        FileOutputFormat.setOutputPath(job,newPath(otherArgs[1]));
        System.exit(job.waitForCompletion(true) ? 0: 1);
    }
}

在 Eclipse 控制台中的结果如下:

a  9,9,9,9,
.......................
a  3,4,70,9,
----------------------
a  
>>>>>>>>>>>>>>>>>>>>>>
b  8,8,8,
.......................
b  50,60,8,
----------------------
b  
>>>>>>>>>>>>>>>>>>>>>>

关于第 1 个坑:对象重用( objects reuse 

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一个对象(例如Text store = new Text(value) 或者 String a = value.toString()),而不能直接赋引用。因为引用从始至终都是指向同一个对象,你如果直接保存它们,那最后它们都指向最后一个输入记录。会影响最终计算结果而出错。 

看到这里,我想你会恍然大悟:这不是刚毕业找工作,面试官常问的问题:String 是不可变对象但为什么能相加呢?为什么字符串相加不提倡用 String,而用 StringBuilder ?如果你还不清楚这个问题怎么回答,建议你看看这篇深入理解 String, StringBuffer 与 StringBuilder 的区别http://my.oschina.net/leejun2005/blog/102377

关于第 2 个坑:http://stackoverflow.com/questions/6111248/iterate-twice-on-values

The Iterator you receive from that Iterable's iterator() method is special. The values may not all be in memory; Hadoop may be streaming them from disk. They aren't really backed by a Collection, so it's nontrivial to allow multiple iterations.

最后想说明的是:hadoop 框架的作者们真的是考虑很周全,在 hadoop 框架中,不仅有对象重用,还有 JVM 重用等,节约一切可以节约的资源,提高一切可以提高的性能。因为在这种海量数据处理的场景下,性能优化是非常重要的,你可能处理100条数据体现不出性能差别,但是你面对的是千亿、万亿级别的数据呢?

PS:

我的代码是在 Eclipse 中远程调试的,所以 reduce 是没有写 hdfs 的,直接在 eclipse 终端上可以看到结果,很方便,关于怎么在 windows 上远程调试 hadoop,请参考这里 《实战 windows7 下 eclipse 远程调试 linux hadoophttp://my.oschina.net/leejun2005/blog/122775

REF:

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

http://paddy-w.iteye.com/blog/1514595

关于 hadoop 中 JVM 重用和对象重用的介绍

http://wikidoop.com/wiki/Hadoop/MapReduce/Reducer

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值