01 package com.test;
02  
03 import java.util.ArrayList;
04 import java.util.Iterator;
05 import java.util.List;
06  
07 public class T
{
08  
09     public static void main(String[]
args) {
10  
11         //
只要实现了Iterable接口的对象都可以使用for-each循环。
12         //
Iterable接口只由iterator方法构成,
13         //
iterator()方法是java.lang.Iterable接口,被Collection继承。
14         /*public
interface Iterable<T> {
15             Iterator<T>
iterator();
16         }*/
17         Iterable<String>
iter = 
new Iterable<String>()
{
18             public Iterator<String>
iterator() {
19                 List<String>
l = 
new ArrayList<String>();
20                 l.add("aa");
21                 l.add("bb");
22                 l.add("cc");
23                 return l.iterator();
24             }
25         };
26         for(int count
new int[]
{
12}){
27             for (String
item : iter) {
28                 System.out.println(item);
29             }
30             System.out.println("---------->>
"
 +
count + 
"
END."
);
31         }
32     }
33 }

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

我们先看一段测试代码:

测试数据:

1 3
2 4
3 50
4 60
5 70
6 8
7 9
01 import java.io.IOException;
02 import java.util.ArrayList;
03 import java.util.List;
04  
05 import org.apache.hadoop.conf.Configuration;
06 import org.apache.hadoop.fs.FileSystem;
07 import org.apache.hadoop.fs.Path;
08 import org.apache.hadoop.io.Text;
09 import org.apache.hadoop.mapreduce.Job;
10 import org.apache.hadoop.mapreduce.Mapper;
11 import org.apache.hadoop.mapreduce.Reducer;
12 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
13 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
14 import org.apache.hadoop.util.GenericOptionsParser;
15  
16 public class TestIterable
{
17  
18     public static class M1 extends Mapper<Object,
Text, Text, Text> {
19         private Text
oKey = 
new Text();
20         private Text
oVal = 
new Text();
21         String[]
lineArr;
22  
23         public void map(Object
key, Text value, Context context) 
throws IOException,
InterruptedException {
24             lineArr
= value.toString().split(
"
"
);
25             oKey.set(lineArr[0]);
26             oVal.set(lineArr[1]);
27             context.write(oKey,
oVal);
28         }
29     }
30  
31     public static class R1 extends Reducer<Text,
Text, Text, Text> {
32         List<String>
valList = 
new ArrayList<String>();
33         List<Text>
textList = 
new ArrayList<Text>();
34         String
strAdd;
35         public void reduce(Text
key, Iterable<Text> values, Context context) 
throws IOException,
36                 InterruptedException
{
37             valList.clear();
38             textList.clear();
39             strAdd
"";
40             for (Text
val : values) {
41                 valList.add(val.toString());
42                 textList.add(val);
43             }
44              
45             //
坑之 1 :为神马输出的全是最后一个值?why?
46             for(Text
text : textList){
47                 strAdd
+= text.toString() + 
",
"
;
48             }
49             System.out.println(key.toString()
"\t" +
strAdd);
50             System.out.println(".......................");
51              
52             //
我这样干呢?对了吗?
53             strAdd
"";
54             for(String
val : valList){
55                 strAdd
+= val + 
",
"
;
56             }
57             System.out.println(key.toString()
"\t" +
strAdd);
58             System.out.println("----------------------");
59              
60             //
坑之 2 :第二次遍历的时候为什么得到的都是空?why?
61             valList.clear();
62             strAdd
"";
63             for (Text
val : values) {
64                 valList.add(val.toString());
65             }
66             for(String
val : valList){
67                 strAdd
+= val + 
",
"
;
68             }
69             System.out.println(key.toString()
"\t" +
strAdd);
70             System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
71         }
72     }
73  
74     public static void main(String[]
args) 
throws Exception
{
75         Configuration
conf = 
new Configuration();
76         conf.set("mapred.job.queue.name""regular");
77         String[]
otherArgs = 
new GenericOptionsParser(conf,
args).getRemainingArgs();
78         if (otherArgs.length
!= 
2)
{
79             System.err.println("Usage:
wordcount <in> <out>"
);
80             System.exit(2);
81         }
82         System.out.println("------------------------");
83         Job
job = 
new Job(conf, "TestIterable");
84         job.setJarByClass(TestIterable.class);
85         job.setMapperClass(M1.class);
86         job.setReducerClass(R1.class);
87         job.setOutputKeyClass(Text.class);
88         job.setOutputValueClass(Text.class);
89         //
输入输出路径
90         FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
91         FileSystem.get(conf).delete(new Path(otherArgs[1]), true);
92         FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
93         System.exit(job.waitForCompletion(true)
0 1);
94     }
95 }

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

01 a   9999,
02 .......................
03 a   34709,
04 ----------------------
05 a  
06 >>>>>>>>>>>>>>>>>>>>>>
07 b   888,
08 .......................
09 b   50608,
10 ----------------------
11 b  
12 >>>>>>>>>>>>>>>>>>>>>>

关于第 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 hadoop》http://my.oschina.net/leejun2005/blog/122775

REF:

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

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

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

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

hadoop reduce 阶段遍历 Iterable 的 2 个“坑”的更多相关文章

  1. reduce 阶段遍历对象添加到ArrayList中的问题

    起初遍历values时直接把对象添加到集合中,后来输出结果和预期不符,debug时发现添加到集合中的对象的值全部是最后一个对象的值,网上百度了下,发现是reduce阶段对象重用的问题,reduce阶段 ...

  2. 大数据 : Hadoop reduce阶段

    Mapreduce中由于sort的存在,MapTask和ReduceTask直接是工作流的架构.而不是数据流的架构.在MapTask尚未结束,其输出结果尚未排序及合并前,ReduceTask是又有数据 ...

  3. Hadoop提供的reduce函数中Iterable 接口只能遍历一次的问题

    今天在写MapReduce中的reduce函数时,碰到个问题,特此记录一下: void reduce(key, Iterable<*>values,...) { for(* v:value ...

  4. 9.2.3 hadoop reduce端连接-分区分组聚合

    1.1.1         reduce端连接-分区分组聚合 reduce端连接则是利用了reduce的分区功能将stationid相同的分到同一个分区,在利用reduce的分组聚合功能,将同一个st ...

  5. Hadoop API:遍历文件分区目录,并根据目录下的数据进行并行提交spark任务

    hadoop api提供了一些遍历文件的api,通过该api可以实现遍历文件目录: import java.io.FileNotFoundException; import java.io.IOExc ...

  6. MapReduce (hive表SequenceFile的结果做输入)、MultipleOutputs和Reduce端迭代iterable的一些说明

    很长时间以来一直写hive,嵌套脚本.偶尔写UDF.  最近用Hive的dynamic partition和多路插入做一些事情,很遗憾的结果是非常不稳定,有时能成功,有时失败.(可能是因为hive版本 ...

  7. hive reduce 阶段GC Exception

    某个reduce中的value堆积的对象过多,导致jvm频繁GC. 解决办法: 1. 增加reduce个数,set mapred.reduce.tasks=300,. 2. 在hive-site.xm ...

  8. Hadoop第一阶段总结

    来自为知笔记(Wiz)

  9. 工作中Hadoop,Spark,Phoenix,Impala 集群中遇到坑及解决方案

    1.HDFS 修复 问题描述:其他部门在yarn平台上跑spark 程序错误的生成了海量的不到100K的小文件,导致namenode压力过大,其中一个namenode宕机后,没有及时发现 使得edit ...

随机推荐

  1. JS 调用存储过程传递参数

    引用 #region 程序集 Newtonsoft.Json.dll, v4.5.0.0 // E:\Newtonsoft.Json.dll #endregion public DataTable R ...

  2. nginx的报错500

    500:服务器内部错误,也就是服务器遇到意外情况,而无法履行请求. 500错误一般有几种情况: 1. web脚本错误,如php语法错误,lua语法错误等. 2. 访问量大的时候,由于系统资源限制,而不 ...

  3. hdu6060[贪心+dfs] 2017多校3

    /* hdu6060[贪心+dfs] 2017多校3*/ #include <bits/stdc++.h> using namespace std; typedef long long L ...

  4. 【Luogu】P1393动态逆序对(树套树)

    题目链接 树套树. 每次删掉x的时候会减去1到x-1里比x位置的数大的数和它构成的逆序对,以及x+1到n里比x位置的数小的数和它构成的逆序对. 顺带一提我发现平衡树insert的时候不是要splay一 ...

  5. 【Luogu】P2894酒店Hotel(线段树)

    题目链接 我好蒻啊   题题看题解 线段树维护从左端点开始的最长连续空房.右端点结束的最长连续空房.整段区间的最长连续空房.区间非空房的个数. http://blog.csdn.net/qq_3955 ...

  6. BZOJ 3757 苹果树 ——莫队算法

    挺好的一道题目,怎么就没有版权了呢?大数据拍过了,精神AC.... 发现几种颜色这性质比较垃圾,不可加,莫队硬上. %了一发popoqqq大神的博客, 看了一波VFK关于糖果公园的博客, 又找了wjm ...

  7. [BZOJ1604] [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居(好题)

    传送门 良心题解 #include <set> #include <cstdio> #include <iostream> #include <algorit ...

  8. 【单调队列】bzoj 1407 [HAOI2007]理想的正方形

    [题意] 给定一个n*m的矩阵,求所有大小为k*k的正方形中(最大值-最小值)的最小值 [思路] 先横着算出每一行的长度为k的窗口内的最大值,变成一个n*(m-k+1)的矩阵mx 再竖着算出每一列的长 ...

  9. BZOJ 4808 马 二分图最大独立集

    题目应该就是最大独立集了吧,没什么了,平面图求最大独立集需要/2的, WQH说加直接+双向边考研过,结果真的过了,应该是匈牙利算法寻找的 时候更加快了吧.(方便找边) #include<cstd ...

  10. 纯干货,Mysql innodb的ACID特性是怎么实现的?以及高并发情况下会出现的问题

    首先说说什么是ACID: 它们分别是Atomicity(原子性),Consistency(一致性),Isolation(隔离性),Transaction(持久性) 原子性: 意为单个事务里的多个操作要 ...