1. 程式人生 > >MapReduce框架中Key-Value物件的重用

MapReduce框架中Key-Value物件的重用

從程式碼看問題

@Override
        protected void reduce(Text key, Iterable<Text> values,Context context)
                throws IOException, InterruptedException {
            List<Text> list =new ArrayList<String>();
            int sum=0;
            for(Text val : values){
                list.add(val);
            }
            for
(Text text : list){ // 總是輸出values列表中最後一個值 System.out.println(text.toString()); }

這是因為MapReduce框架對Key物件和Value物件重用

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()),而不能直接賦引用。因為引用從始至終都是指向同一個物件,你如果直接儲存它們,那最後它們都指向最後一個輸入記錄。會影響最終計算結果而出錯。