MapReduce源码解析--环形缓冲区

开发 开发工具
这篇文章把Map阶段的环形缓冲区单独拿出来进行分析,对环形缓冲区的数据结构和数据进入环形缓冲区然后溢写到磁盘的流程进行分析。

这篇文章把Map阶段的环形缓冲区单独拿出来进行分析,对环形缓冲区的数据结构和数据进入环形缓冲区然后溢写到磁盘的流程进行分析。

环形缓冲区数据结构

Map过程中环形缓冲区是指数据被map处理之后会先放入内存,内存中的这片区域就是环形缓冲区。

环形缓冲区是在MapTask.MapOutputBuffer中定义的,相关的属性如下:

  1. // k/v accounting 
  2. // 存放meta数据的IntBuffer,都是int entry,占4byte 
  3. private IntBuffer kvmeta; // metadata overlay on backing store 
  4. int kvstart; // marks origin of spill metadata 
  5. int kvend; // marks end of spill metadata 
  6. int kvindex; // marks end of fully serialized records 
  7. // 分割meta和key value内容的标识 
  8. // meta数据和key value内容都存放在同一个环形缓冲区,所以需要分隔开 
  9. int equator; // marks origin of meta/serialization 
  10. int bufstart; // marks beginning of spill 
  11. int bufend; // marks beginning of collectable 
  12. int bufmark; // marks end of record 
  13. int bufindex; // marks end of collected 
  14. int bufvoid; // marks the point where we should stop 
  15. // reading at the end of the buffer 
  16. // 存放key value的byte数组,单位是byte,注意与kvmeta区分 
  17. byte[] kvbuffer; // main output buffer 
  18. private final byte[] b0 = new byte[0]; 
  19.   
  20. // key value在kvbuffer中的地址存放在偏移kvindex的距离 
  21. private static final int VALSTART = 0; // val offset in acct 
  22. private static final int KEYSTART = 1; // key offset in acct 
  23. // partition信息存在kvmeta中偏移kvindex的距离 
  24. private static final int PARTITION = 2; // partition offset in acct 
  25. private static final int VALLEN = 3; // length of value 
  26. // 一对key value的meta数据在kvmeta中占用的个数 
  27. private static final int NMETA = 4; // num meta ints 
  28. // 一对key value的meta数据在kvmeta中占用的byte数 
  29. private static final int METASIZE = NMETA * 4; // size in bytes 

环形缓冲区其实是一个数组,数组中存放着key、value的序列化数据和key、value的元数据信息,key/value的元数据存储的格式是int类型,每个key/value对应一个元数据,元数据由4个int组成,第一个int存放value的起始位置,第二个存放key的起始位置,第三个存放partition,最后一个存放value的长度。

 

key/value序列化的数据和元数据在环形缓冲区中的存储是由equator分隔的,key/value按照索引递增的方向存储,meta则按照索引递减的方向存储,将其数组抽象为一个环形结构之后,以equator为界,key/value顺时针存储,meta逆时针存储。

初始化

 

环形缓冲区的结构在MapOutputBuffer.init中创建。

  1. public void init(MapOutputCollector.Context context 
  2. ) throws IOException, ClassNotFoundException { 
  3. ... 
  4. //MAP_SORT_SPILL_PERCENT = mapreduce.map.sort.spill.percent 
  5. // map 端buffer所占的百分比 
  6. //sanity checks 
  7. final float spillper = 
  8. job.getFloat(JobContext.MAP_SORT_SPILL_PERCENT, (float)0.8); 
  9. //IO_SORT_MB = "mapreduce.task.io.sort.mb" 
  10. // map 端buffer大小 
  11. // mapreduce.task.io.sort.mb * mapreduce.map.sort.spill.percent 最好是16的整数倍 
  12. final int sortmb = job.getInt(JobContext.IO_SORT_MB, 100); 
  13. // 所有的spill index 在内存所占的大小的阈值 
  14. indexCacheMemoryLimit = job.getInt(JobContext.INDEX_CACHE_MEMORY_LIMIT, 
  15. INDEX_CACHE_MEMORY_LIMIT_DEFAULT); 
  16. ... 
  17. // 排序的实现类,可以自己实现。 这里用的是改写的快排 
  18. sorter = ReflectionUtils.newInstance(job.getClass("map.sort.class", 
  19. QuickSort.class, IndexedSorter.class), job); 
  20. // buffers and accounting 
  21. // 上面IO_SORT_MB的单位是MB,左移20位将单位转化为byte 
  22. int maxMemUsage = sortmb << 20
  23. // METASIZE是元数据的长度,元数据有4个int单元,分别为 
  24. // VALSTART、KEYSTART、PARTITION、VALLEN,而int为4个byte, 
  25. // 所以METASIZE长度为16。下面是计算buffer中最多有多少byte来存元数据 
  26. maxMemUsage -maxMemUsage % METASIZE; 
  27. // 元数据数组 以byte为单位 
  28. kvbuffer = new byte[maxMemUsage]; 
  29. bufvoid = kvbuffer.length; 
  30. // 将kvbuffer转化为int型的kvmeta 以int为单位,也就是4byte 
  31. kvmeta = ByteBuffer.wrap(kvbuffer) 
  32. .order(ByteOrder.nativeOrder()) 
  33. .asIntBuffer(); 
  34. // 设置buf和kvmeta的分界线 
  35. setEquator(0); 
  36. bufstart = bufend = bufindex = equator
  37. kvstart = kvend = kvindex; 
  38. // kvmeta中存放元数据实体的最大个数 
  39. maxRec = kvmeta.capacity() / NMETA; 
  40. // buffer spill时的阈值(不单单是sortmb*spillper) 
  41. // 更加精确的是kvbuffer.length*spiller 
  42. softLimit = (int)(kvbuffer.length * spillper); 
  43. // 此变量较为重要,作为spill的动态衡量标准 
  44. bufferRemaining = softLimit
  45. ... 
  46. // k/v serialization 
  47. comparator = job.getOutputKeyComparator(); 
  48. keyClass = (Class<K>)job.getMapOutputKeyClass(); 
  49. valClass = (Class<V>)job.getMapOutputValueClass(); 
  50. serializationFactory = new SerializationFactory(job); 
  51. keySerializer = serializationFactory.getSerializer(keyClass); 
  52. // 将bb作为key序列化写入的output 
  53. keySerializer.open(bb); 
  54. valSerializer = serializationFactory.getSerializer(valClass); 
  55. // 将bb作为value序列化写入的output 
  56. valSerializer.open(bb); 
  57. ... 
  58. // combiner 
  59. ... 
  60. spillInProgress = false
  61. // 最后一次merge时,在有combiner的情况下,超过此阈值才执行combiner 
  62. minSpillsForCombine = job.getInt(JobContext.MAP_COMBINE_MIN_SPILLS, 3); 
  63. spillThread.setDaemon(true); 
  64. spillThread.setName("SpillThread"); 
  65. spillLock.lock(); 
  66. try { 
  67. spillThread.start(); 
  68. while (!spillThreadRunning) { 
  69. spillDone.await(); 
  70. } catch (InterruptedException e) { 
  71. throw new IOException("Spill thread failed to initialize", e); 
  72. } finally { 
  73. spillLock.unlock(); 
  74. if (sortSpillException != null) { 
  75. throw new IOException("Spill thread failed to initialize", 
  76. sortSpillException); 

init是对环形缓冲区进行初始化构造,由mapreduce.task.io.sort.mb决定map中环形缓冲区的大小sortmb,默认是100M。

此缓冲区也用于存放meta,一个meta占用METASIZE(16byte),则其中用于存放数据的大小是maxMemUsage -= sortmb << 20 % METASIZE(由此可知最好设置sortmb转换为byte之后是16的整数倍),然后用maxMemUsage初始化kvbuffer字节数组和kvmeta整形数组,最后设置数组的一些标识信息。利用setEquator(0)设置kvbuffer和kvmeta的分界线,初始化的时候以0为分界线,kvindex为aligned - METASIZE + kvbuffer.length,其位置在环形数组中相当于按照逆时针方向减去METASIZE,由kvindex设置kvstart = kvend = kvindex,由equator设置bufstart = bufend = bufindex = equator,还得设置bufvoid = kvbuffer.length,bufvoid用于标识用于存放数据的最大位置。

为了提高效率,当buffer占用达到阈值之后,会进行spill,这个阈值是由bufferRemaining进行检查的,bufferRemaining由softLimit = (int)(kvbuffer.length * spillper); bufferRemaining = softLimit;进行初始化赋值,这里需要注意的是softLimit并不是sortmb*spillper,而是kvbuffer.length * spillper,当sortmb << 20是16的整数倍时,才可以认为softLimit是sortmb*spillper。

 

下面是setEquator的代码

  1. // setEquator(0)的代码如下 
  2. private void setEquator(int pos) { 
  3. equator = pos
  4. // set index prior to first entry, aligned at meta boundary 
  5. // 第一个 entry的末尾位置,即元数据和kv数据的分界线 单位是byte 
  6. final int aligned = pos - (pos % METASIZE); 
  7. // Cast one of the operands to long to avoid integer overflow 
  8. // 元数据中存放数据的起始位置 
  9. kvindex = (int) 
  10. (((long)aligned - METASIZE + kvbuffer.length) % kvbuffer.length) / 4; 
  11. LOG.info("(EQUATOR) " + pos + " kvi " + kvindex + 
  12. "(" + (kvindex * 4) + ")"); 

buffer初始化之后的抽象数据结构如下图所示:

buffer初始化之后的抽象数据结构

环形缓冲区数据结构图

写入buffer

 

Map通过NewOutputCollector.write方法调用collector.collect向buffer中写入数据,数据写入之前已在NewOutputCollector.write中对要写入的数据进行逐条分区,下面看下collect

  1. // MapOutputBuffer.collect 
  2. public synchronized void collect(K key, V value, final int partition 
  3. ) throws IOException { 
  4. ... 
  5. // 新数据collect时,先将剩余的空间减去元数据的长度,之后进行判断 
  6. bufferRemaining -METASIZE
  7. if (bufferRemaining <= 0) { 
  8. // start spill if the thread is not running and the soft limit has been 
  9. // reached 
  10. spillLock.lock(); 
  11. try { 
  12. do { 
  13. // 首次spill时,spillInProgress是false 
  14. if (!spillInProgress) { 
  15. // 得到kvindex的byte位置 
  16. final int kvbidx = 4 * kvindex; 
  17. // 得到kvend的byte位置 
  18. final int kvbend = 4 * kvend; 
  19. // serialized, unspilled bytes always lie between kvindex and 
  20. // bufindex, crossing the equator. Note that any void space 
  21. // created by a reset must be included in "used" bytes 
  22. final int bUsed = distanceTo(kvbidx, bufindex); 
  23. final boolean bufsoftlimit = bUsed >= softLimit; 
  24. if ((kvbend + METASIZE) % kvbuffer.length != 
  25. equator - (equator % METASIZE)) { 
  26. // spill finished, reclaim space 
  27. resetSpill(); 
  28. bufferRemaining = Math.min( 
  29. distanceTo(bufindex, kvbidx) - 2 * METASIZE, 
  30. softLimit - bUsed) - METASIZE; 
  31. continue; 
  32. } else if (bufsoftlimit && kvindex != kvend) { 
  33. // spill records, if any collected; check latter, as it may 
  34. // be possible for metadata alignment to hit spill pcnt 
  35. startSpill(); 
  36. final int avgRec = (int) 
  37. (mapOutputByteCounter.getCounter() / 
  38. mapOutputRecordCounter.getCounter()); 
  39. // leave at least half the split buffer for serialization data 
  40. // ensure that kvindex >= bufindex 
  41. final int distkvi = distanceTo(bufindex, kvbidx); 
  42. final int newPos = (bufindex + 
  43. Math.max(2 * METASIZE - 1, 
  44. Math.min(distkvi / 2, 
  45. distkvi / (METASIZE + avgRec) * METASIZE))) 
  46. % kvbuffer.length; 
  47. setEquator(newPos); 
  48. bufmark = bufindex = newPos; 
  49. final int serBound = 4 * kvend; 
  50. // bytes remaining before the lock must be held and limits 
  51. // checked is the minimum of three arcs: the metadata space, the 
  52. // serialization space, and the soft limit 
  53. bufferRemaining = Math.min( 
  54. // metadata max 
  55. distanceTo(bufend, newPos), 
  56. Math.min( 
  57. // serialization max 
  58. distanceTo(newPos, serBound), 
  59. // soft limit 
  60. softLimit)) - 2 * METASIZE; 
  61. } while (false); 
  62. } finally { 
  63. spillLock.unlock(); 
  64. // 将key value 及元数据信息写入缓冲区 
  65. try { 
  66. // serialize key bytes into buffer 
  67. int keystart = bufindex
  68. // 将key序列化写入kvbuffer中,并移动bufindex 
  69. keySerializer.serialize(key); 
  70. // key所占空间被bufvoid分隔,则移动key, 
  71. // 将其值放在连续的空间中便于sort时key的对比 
  72. if (bufindex < keystart) { 
  73. // wrapped the key; must make contiguous 
  74. bb.shiftBufferedKey(); 
  75. keystart = 0
  76. // serialize value bytes into buffer 
  77. final int valstart = bufindex
  78. valSerializer.serialize(value); 
  79. // It's possible for records to have zero length, i.e. the serializer 
  80. // will perform no writes. To ensure that the boundary conditions are 
  81. // checked and that the kvindex invariant is maintained, perform a 
  82. // zero-length write into the buffer. The logic monitoring this could be 
  83. // moved into collect, but this is cleaner and inexpensive. For now, it 
  84. // is acceptable. 
  85. bb.write(b0, 0, 0); 
  86.   
  87. // the record must be marked after the preceding write, as the metadata 
  88. // for this record are not yet written 
  89. int valend = bb.markRecord(); 
  90.   
  91. mapOutputRecordCounter.increment(1); 
  92. mapOutputByteCounter.increment( 
  93. distanceTo(keystart, valend, bufvoid)); 
  94.   
  95. // write accounting info 
  96. kvmeta.put(kvindex + PARTITION, partition); 
  97. kvmeta.put(kvindex + KEYSTART, keystart); 
  98. kvmeta.put(kvindex + VALSTART, valstart); 
  99. kvmeta.put(kvindex + VALLEN, distanceTo(valstart, valend)); 
  100. // advance kvindex 
  101. kvindex = (kvindex - NMETA + kvmeta.capacity()) % kvmeta.capacity(); 
  102. } catch (MapBufferTooSmallException e) { 
  103. LOG.info("Record too large for in-memory buffer: " + e.getMessage()); 
  104. spillSingleRecord(key, value, partition); 
  105. mapOutputRecordCounter.increment(1); 
  106. return; 

每次写入数据时,执行bufferRemaining -= METASIZE之后,检查bufferRemaining,

 

如果大于0,直接将key/value序列化对和对应的meta写入buffer中,key/value是序列化之后写入的,key/value经过一些列的方法调用Serializer.serialize(key/value) -> WritableSerializer.serialize(key/value) -> BytesWritable.write(dataOut) -> DataOutputStream.write(bytes, 0, size) -> MapOutputBuffer.Buffer.write(b, off, len),最后由MapOutputBuffer.Buffer.write(b, off, len)将数据写入kvbuffer中,write方法如下:

  1. public void write(byte b[], int off, int len) 
  2. throws IOException { 
  3. // must always verify the invariant that at least METASIZE bytes are 
  4. // available beyond kvindex, even when len == 0 
  5. bufferRemaining -len
  6. if (bufferRemaining <= 0) { 
  7. // writing these bytes could exhaust available buffer space or fill 
  8. // the buffer to soft limit. check if spill or blocking are necessary 
  9. boolean blockwrite = false
  10. spillLock.lock(); 
  11. try { 
  12. do { 
  13. checkSpillException(); 
  14.   
  15. final int kvbidx = 4 * kvindex; 
  16. final int kvbend = 4 * kvend; 
  17. // ser distance to key index 
  18. final int distkvi = distanceTo(bufindex, kvbidx); 
  19. // ser distance to spill end index 
  20. final int distkve = distanceTo(bufindex, kvbend); 
  21.   
  22. // if kvindex is closer than kvend, then a spill is neither in 
  23. // progress nor complete and reset since the lock was held. The 
  24. // write should block only if there is insufficient space to 
  25. // complete the current write, write the metadata for this record, 
  26. // and write the metadata for the next record. If kvend is closer, 
  27. // then the write should block if there is too little space for 
  28. // either the metadata or the current write. Note that collect 
  29. // ensures its metadata requirement with a zero-length write 
  30. blockwrite = distkvi <= distkve 
  31. ? distkvi <= len + 2 * METASIZE 
  32. : distkve <= len || distanceTo(bufend, kvbidx) < 2 * METASIZE; 
  33.   
  34. if (!spillInProgress) { 
  35. if (blockwrite) { 
  36. if ((kvbend + METASIZE) % kvbuffer.length != 
  37. equator - (equator % METASIZE)) { 
  38. // spill finished, reclaim space 
  39. // need to use meta exclusively; zero-len rec & 100% spill 
  40. // pcnt would fail 
  41. resetSpill(); // resetSpill doesn't move bufindex, kvindex 
  42. bufferRemaining = Math.min( 
  43. distkvi - 2 * METASIZE, 
  44. softLimit - distanceTo(kvbidx, bufindex)) - len; 
  45. continue; 
  46. // we have records we can spill; only spill if blocked 
  47. if (kvindex != kvend) { 
  48. startSpill(); 
  49. // Blocked on this write, waiting for the spill just 
  50. // initiated to finish. Instead of repositioning the marker 
  51. // and copying the partial record, we set the record start 
  52. // to be the new equator 
  53. setEquator(bufmark); 
  54. } else { 
  55. // We have no buffered records, and this record is too large 
  56. // to write into kvbuffer. We must spill it directly from 
  57. // collect 
  58. final int size = distanceTo(bufstart, bufindex) + len; 
  59. setEquator(0); 
  60. bufstart = bufend = bufindex = equator
  61. kvstart = kvend = kvindex; 
  62. bufvoid = kvbuffer.length; 
  63. throw new MapBufferTooSmallException(size + " bytes"); 
  64.   
  65. if (blockwrite) { 
  66. // wait for spill 
  67. try { 
  68. while (spillInProgress) { 
  69. reporter.progress(); 
  70. spillDone.await(); 
  71. } catch (InterruptedException e) { 
  72. throw new IOException( 
  73. "Buffer interrupted while waiting for the writer", e); 
  74. } while (blockwrite); 
  75. } finally { 
  76. spillLock.unlock(); 
  77. // here, we know that we have sufficient space to write 
  78. if (bufindex + len > bufvoid) { 
  79. final int gaplen = bufvoid - bufindex; 
  80. System.arraycopy(b, off, kvbuffer, bufindex, gaplen); 
  81. len -gaplen
  82. off += gaplen; 
  83. bufindex = 0
  84. System.arraycopy(b, off, kvbuffer, bufindex, len); 
  85. bufindex += len; 

write方法将key/value写入kvbuffer中,如果bufindex+len超过了bufvoid,则将写入的内容分开存储,将一部分写入bufindex和bufvoid之间,然后重置bufindex,将剩余的部分写入,这里不区分key和value,写入key之后会在collect中判断bufindex < keystart,当bufindex小时,则key被分开存储,执行bb.shiftBufferedKey(),value则直接写入,不用判断是否被分开存储,key不能分开存储是因为要对key进行排序。

这里需要注意的是要写入的数据太长,并且kvinde==kvend,则抛出MapBufferTooSmallException异常,在collect中捕获,将此数据直接spill到磁盘spillSingleRecord,也就是当单条记录过长时,不写buffer,直接写入磁盘。

 

下面看下bb.shiftBufferedKey()代码

  1. // BlockingBuffer.shiftBufferedKey 
  2. protected void shiftBufferedKey() throws IOException { 
  3. // spillLock unnecessary; both kvend and kvindex are current 
  4. int headbytelen = bufvoid - bufmark; 
  5. bufvoid = bufmark
  6. final int kvbidx = 4 * kvindex; 
  7. final int kvbend = 4 * kvend; 
  8. final int avail = 
  9. Math.min(distanceTo(0, kvbidx), distanceTo(0, kvbend)); 
  10. if (bufindex + headbytelen < avail) { 
  11. System.arraycopy(kvbuffer, 0, kvbuffer, headbytelen, bufindex); 
  12. System.arraycopy(kvbuffer, bufvoid, kvbuffer, 0, headbytelen); 
  13. bufindex += headbytelen; 
  14. bufferRemaining -kvbuffer.length - bufvoid; 
  15. } else { 
  16. byte[] keytmp = new byte[bufindex]; 
  17. System.arraycopy(kvbuffer, 0, keytmp, 0, bufindex); 
  18. bufindex = 0
  19. out.write(kvbuffer, bufmark, headbytelen); 
  20. out.write(keytmp); 

shiftBufferedKey时,判断首部是否有足够的空间存放key,有没有足够的空间,则先将首部的部分key写入keytmp中,然后分两次写入,再次调用Buffer.write,如果有足够的空间,分两次copy,先将首部的部分key复制到headbytelen的位置,然后将末尾的部分key复制到首部,移动bufindex,重置bufferRemaining的值。

key/value写入之后,继续写入元数据信息并重置kvindex的值。

spill

 

一次写入buffer结束,当写入数据比较多,bufferRemaining小于等于0时,准备进行spill,首次spill,spillInProgress为false,此时查看bUsed = distanceTo(kvbidx, bufindex),此时bUsed >= softLimit 并且 (kvbend + METASIZE) % kvbuffer.length == equator - (equator % METASIZE),则进行spill,调用startSpill

  1. private void startSpill() { 
  2. // 元数据的边界赋值 
  3. kvend = (kvindex + NMETA) % kvmeta.capacity(); 
  4. // key/value的边界赋值 
  5. bufend = bufmark
  6. // 设置spill运行标识 
  7. spillInProgress = true
  8. ... 
  9. // 利用重入锁,对spill线程进行唤醒 
  10. spillReady.signal(); 

startSpill唤醒spill线程之后,进程spill操作,但此时map向buffer的写入操作并没有阻塞,需要重新边界equator和bufferRemaining的值,先来看下equator和bufferRemaining值的设定:

  1. // 根据已经写入的kv得出每个record的平均长度 
  2. final int avgRec = (int) (mapOutputByteCounter.getCounter() / 
  3. mapOutputRecordCounter.getCounter()); 
  4. // leave at least half the split buffer for serialization data 
  5. // ensure that kvindex >= bufindex 
  6. // 得到空余空间的大小 
  7. final int distkvi = distanceTo(bufindex, kvbidx); 
  8. // 得出新equator的位置 
  9. final int newPos = (bufindex + 
  10. Math.max(2 * METASIZE - 1, 
  11. Math.min(distkvi / 2, 
  12. distkvi / (METASIZE + avgRec) * METASIZE))) 
  13. % kvbuffer.length; 
  14. setEquator(newPos); 
  15. bufmark = bufindex = newPos; 
  16. final int serBound = 4 * kvend; 
  17. // bytes remaining before the lock must be held and limits 
  18. // checked is the minimum of three arcs: the metadata space, the 
  19. // serialization space, and the soft limit 
  20. bufferRemaining = Math.min( 
  21. // metadata max 
  22. distanceTo(bufend, newPos), 
  23. Math.min( 
  24. // serialization max 
  25. distanceTo(newPos, serBound), 
  26. // soft limit 
  27. softLimit)) - 2 * METASIZE; 

因为equator是kvbuffer和kvmeta的分界线,为了更多的空间存储kv,则最多拿出distkvi的一半来存储meta,并且利用avgRec估算distkvi能存放多少个record和meta对,根据record和meta对的个数估算meta所占空间的大小,从distkvi/2和meta所占空间的大小中取最小值,又因为distkvi中最少得存放一个meta,所占空间为METASIZE,在选取kvindex时需要求aligned,aligned最多为METASIZE-1,总和上述因素,最终选取equator为(bufindex + Math.max(2 * METASIZE - 1, Math.min(distkvi / 2, distkvi / (METASIZE + avgRec) * METASIZE)))。equator选取之后,设置bufmark = bufindex = newPos和kvindex,但此时并不设置bufstart、bufend和kvstart、kvend,因为这几个值要用来表示spill数据的边界。

spill之后,可用的空间减少了,则控制spill的bufferRemaining也应该重新设置,bufferRemaining取三个值的最小值减去2*METASIZE,三个值分别是meta可用占用的空间distanceTo(bufend, newPos),kv可用空间distanceTo(newPos, serBound)和softLimit。这里为什么要减去2*METASIZE,一个是spill之前kvend到kvindex的距离,另一个是当时的kvindex空间????此时,已有一个record要写入buffer,需要从bufferRemaining中减去当前record的元数据占用的空间,即减去METASIZE,另一个METASIZE是在计算equator时,没有包括kvindex到kvend(spill之前)的这段METASIZE,所以要减去这个METASIZE。

 

接下来解析下SpillThread线程,查看其run方法:

  1. public void run() { 
  2. spillLock.lock(); 
  3. spillThreadRunning = true
  4. try { 
  5. while (true) { 
  6. spillDone.signal(); 
  7. // 判断是否在spill,false则挂起SpillThread线程,等待唤醒 
  8. while (!spillInProgress) { 
  9. spillReady.await(); 
  10. try { 
  11. spillLock.unlock(); 
  12. // 唤醒之后,进行排序和溢写到磁盘 
  13. sortAndSpill(); 
  14. } catch (Throwable t) { 
  15. sortSpillException = t; 
  16. } finally { 
  17. spillLock.lock(); 
  18. if (bufend < bufstart) { 
  19. bufvoid = kvbuffer.length; 
  20. kvstart = kvend
  21. bufstart = bufend
  22. spillInProgress = false
  23. } catch (InterruptedException e) { 
  24. Thread.currentThread().interrupt(); 
  25. } finally { 
  26. spillLock.unlock(); 
  27. spillThreadRunning = false

run中主要是sortAndSpill,

  1. private void sortAndSpill() throws IOException, ClassNotFoundException, 
  2. InterruptedException { 
  3. //approximate the length of the output file to be the length of the 
  4. //buffer + header lengths for the partitions 
  5. final long size = distanceTo(bufstart, bufend, bufvoid) + 
  6. partitions * APPROX_HEADER_LENGTH; 
  7. FSDataOutputStream out = null
  8. try { 
  9. // create spill file 
  10. // 用来存储index文件 
  11. final SpillRecord spillRec = new SpillRecord(partitions); 
  12. // 创建写入磁盘的spill文件 
  13. final Path filename = 
  14. mapOutputFile.getSpillFileForWrite(numSpills, size); 
  15. // 打开文件流 
  16. out = rfs.create(filename); 
  17. // kvend/4 是截止到当前位置能存放多少个元数据实体 
  18. final int mstart = kvend / NMETA; 
  19. // kvstart 处能存放多少个元数据实体 
  20. // 元数据则在mstart和mend之间,(mstart - mend)则是元数据的个数 
  21. final int mend = 1 + // kvend is a valid record 
  22. (kvstart >= kvend 
  23. ? kvstart 
  24. : kvmeta.capacity() + kvstart) / NMETA; 
  25. // 排序 只对元数据进行排序,只调整元数据在kvmeta中的顺序 
  26. // 排序规则是MapOutputBuffer.compare, 
  27. // 先对partition进行排序其次对key值排序 
  28. sorter.sort(MapOutputBuffer.this, mstart, mend, reporter); 
  29. int spindex = mstart
  30. // 创建rec,用于存放该分区在数据文件中的信息 
  31. final IndexRecord rec = new IndexRecord(); 
  32. final InMemValBytes value = new InMemValBytes(); 
  33. for (int i = 0; i < partitions; ++i) { 
  34. // 临时文件是IFile格式的 
  35. IFile.Writer<K, V> writer = null
  36. try { 
  37. long segmentStart = out.getPos(); 
  38. FSDataOutputStream partitionOut = CryptoUtils.wrapIfNecessary(job, out); 
  39. writer = new Writer<K, V>(job, partitionOut, keyClass, valClass, codec, 
  40. spilledRecordsCounter); 
  41. // 往磁盘写数据时先判断是否有combiner 
  42. if (combinerRunner == null) { 
  43. // spill directly 
  44. DataInputBuffer key = new DataInputBuffer(); 
  45. // 写入相同partition的数据 
  46. while (spindex < mend && 
  47. kvmeta.get(offsetFor(spindex % maxRec) + PARTITION) == i) { 
  48. final int kvoff = offsetFor(spindex % maxRec); 
  49. int keystart = kvmeta.get(kvoff + KEYSTART); 
  50. int valstart = kvmeta.get(kvoff + VALSTART); 
  51. key.reset(kvbuffer, keystart, valstart - keystart); 
  52. getVBytesForOffset(kvoff, value); 
  53. writer.append(key, value); 
  54. ++spindex; 
  55. } else { 
  56. int spstart = spindex
  57. while (spindex < mend && 
  58. kvmeta.get(offsetFor(spindex % maxRec) 
  59. + PARTITION) == i) { 
  60. ++spindex; 
  61. // Note: we would like to avoid the combiner if we've fewer 
  62. // than some threshold of records for a partition 
  63. if (spstart != spindex) { 
  64. combineCollector.setWriter(writer); 
  65. RawKeyValueIterator kvIter = 
  66. new MRResultIterator(spstart, spindex); 
  67. combinerRunner.combine(kvIter, combineCollector); 
  68.   
  69. // close the writer 
  70. writer.close(); 
  71.   
  72. // record offsets 
  73. // 记录当前partition i的信息写入索文件rec中 
  74. rec.startOffset = segmentStart
  75. rec.rawLength = writer.getRawLength() + CryptoUtils.cryptoPadding(job); 
  76. rec.partLength = writer.getCompressedLength() + CryptoUtils.cryptoPadding(job); 
  77. // spillRec中存放了spill中partition的信息,便于后续堆排序时,取出partition相关的数据进行排序 
  78. spillRec.putIndex(rec, i); 
  79.   
  80. writer = null
  81. } finally { 
  82. if (null != writer) writer.close(); 
  83. // 判断内存中的index文件是否超出阈值,超出则将index文件写入磁盘 
  84. // 当超出阈值时只是把当前index和之后的index写入磁盘 
  85. if (totalIndexCacheMemory >= indexCacheMemoryLimit) { 
  86. // create spill index file 
  87. // 创建index文件 
  88. Path indexFilename = 
  89. mapOutputFile.getSpillIndexFileForWrite(numSpills, partitions 
  90. * MAP_OUTPUT_INDEX_RECORD_LENGTH); 
  91. spillRec.writeToFile(indexFilename, job); 
  92. } else { 
  93. indexCacheList.add(spillRec); 
  94. totalIndexCacheMemory += 
  95. spillRec.size() * MAP_OUTPUT_INDEX_RECORD_LENGTH; 
  96. LOG.info("Finished spill " + numSpills); 
  97. ++numSpills; 
  98. } finally { 
  99. if (out != null) out.close(); 

ortAndSpill中,有mstart和mend得到一共有多少条record需要spill到磁盘,调用sorter.sort对meta进行排序,先对partition进行排序,然后按key排序,排序的结果只调整meta的顺序。

排序之后,判断是否有combiner,没有则直接将record写入磁盘,写入时是一个partition一个IndexRecord,如果有combiner,则将该partition的record写入kvIter,然后调用combinerRunner.combine执行combiner。

写入磁盘之后,将spillx.out对应的spillRec放入内存indexCacheList.add(spillRec),如果所占内存totalIndexCacheMemory超过了indexCacheMemoryLimit,则创建index文件,将此次及以后的spillRec写入index文件存入磁盘。

最后spill次数递增。sortAndSpill结束之后,回到run方法中,执行finally中的代码,对kvstart和bufstart赋值,kvstart = kvend,bufstart = bufend,设置spillInProgress的状态为false。

 

在spill的同时,map往buffer的写操作并没有停止,依然在调用collect,再次回到collect方法中,

  1. // MapOutputBuffer.collect 
  2. public synchronized void collect(K key, V value, final int partition 
  3. ) throws IOException { 
  4. ... 
  5. // 新数据collect时,先将剩余的空间减去元数据的长度,之后进行判断 
  6. bufferRemaining -METASIZE
  7. if (bufferRemaining <= 0) { 
  8. // start spill if the thread is not running and the soft limit has been 
  9. // reached 
  10. spillLock.lock(); 
  11. try { 
  12. do { 
  13. // 首次spill时,spillInProgress是false 
  14. if (!spillInProgress) { 
  15. // 得到kvindex的byte位置 
  16. final int kvbidx = 4 * kvindex; 
  17. // 得到kvend的byte位置 
  18. final int kvbend = 4 * kvend; 
  19. // serialized, unspilled bytes always lie between kvindex and 
  20. // bufindex, crossing the equator. Note that any void space 
  21. // created by a reset must be included in "used" bytes 
  22. final int bUsed = distanceTo(kvbidx, bufindex); 
  23. final boolean bufsoftlimit = bUsed >= softLimit; 
  24. if ((kvbend + METASIZE) % kvbuffer.length != 
  25. equator - (equator % METASIZE)) { 
  26. // spill finished, reclaim space 
  27. resetSpill(); 
  28. bufferRemaining = Math.min( 
  29. distanceTo(bufindex, kvbidx) - 2 * METASIZE, 
  30. softLimit - bUsed) - METASIZE; 
  31. continue; 
  32. } else if (bufsoftlimit && kvindex != kvend) { 
  33. ... 
  34. } while (false); 
  35. } finally { 
  36. spillLock.unlock(); 
  37. ... 

有新的record需要写入buffer时,判断bufferRemaining -= METASIZE,此时的bufferRemaining是在开始spill时被重置过的(此时的bufferRemaining应该比初始的softLimit要小),当bufferRemaining小于等于0时,进入if,此时spillInProgress的状态为false,进入if (!spillInProgress),startSpill时对kvend和bufend进行了重置,则此时(kvbend + METASIZE) % kvbuffer.length != equator - (equator % METASIZE),调用resetSpill(),将kvstart、kvend和bufstart、bufend设置为上次startSpill时的位置。此时buffer已将一部分内容写入磁盘,有大量空余的空间,则对bufferRemaining进行重置,此次不spill。

bufferRemaining取值为Math.min(distanceTo(bufindex, kvbidx) - 2 * METASIZE, softLimit - bUsed) - METASIZE

 

最后一个METASIZE是当前record进入collect之后bufferRemaining减去的那个METASIZE,为什么要减去2*METASIZE,不知道。。。。。

  1. private void resetSpill() { 
  2. final int e = equator
  3. bufstart = bufend = e; 
  4. final int aligned = e - (e % METASIZE); 
  5. // set start/end to point to first meta record 
  6. // Cast one of the operands to long to avoid integer overflow 
  7. kvstart = kvend = (int) 
  8. (((long)aligned - METASIZE + kvbuffer.length) % kvbuffer.length) / 4; 
  9. LOG.info("(RESET) equator " + e + " kv " + kvstart + "(" + 
  10. (kvstart * 4) + ")" + " kvi " + kvindex + "(" + (kvindex * 4) + ")"); 

当bufferRemaining再次小于等于0时,进行spill,这以后就都是套路了。环形缓冲区分析到此结束。

【本文为51CTO专栏作者“王森丰”的原创稿件,转载请注明出处】

戳这里,看该作者更多好文

责任编辑:赵宁宁 来源: 51CTO专栏
相关推荐

2023-10-09 23:01:09

MySQL数据库

2021-06-26 07:50:20

STM32串口开发环形缓冲区

2011-12-14 16:30:42

javanio

2019-02-27 13:58:29

漏洞缓冲区溢出系统安全

2017-01-09 17:03:34

2018-11-01 08:31:05

2011-03-23 12:39:44

2014-07-30 11:21:46

2011-03-23 11:35:00

2009-11-16 17:26:17

Oracle优化缓冲区

2018-01-26 14:52:43

2009-11-16 17:08:59

Oracle日志缓冲区

2009-07-15 15:50:48

Jython线程

2009-11-16 16:59:24

Oracle优化库高速

2009-09-24 18:16:40

2011-07-20 10:54:14

C++

2010-12-27 10:21:21

2010-10-09 14:45:48

2015-03-06 17:09:10

2020-08-10 08:37:32

漏洞安全数据
点赞
收藏

51CTO技术栈公众号