关于reduce中遍历2次数据的问题

来源:互联网 发布:网络兼职业务员 编辑:程序博客网 时间:2024/06/10 18:25

关于reduce中遍历2次数据的问题

@(HADOOP)[hadoop]

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

解决办法:先用一个HashSet将values的各个值保存下来,然后再遍历这个HashSet。

@Override    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {        Set<String> outputValues = new HashSet<>();        int sum = 0;        //计算某个UDID在某个时间段出现LBS信息的总次数。        for(Text value : values){            outputValues.add(value.toString());            String[] valueContent  = value.toString().trim().split(TAB_SEPERATOR);            int count  = Integer.parseInt(valueContent[2]);            sum += count;        }        //debug log        //注意:reduce中key/value对象重用的问题:https://my.oschina.net/leejun2005/blog/131744        if(sum >= LBS_FREQUENCE_THREADHOLD_TO_RETAIN){            for(String value : outputValues){                context.write(key, new Text(value));            }        }    }

详细可参考:https://my.oschina.net/leejun2005/blog/131744

阅读全文
0 0
原创粉丝点击