自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

MapReduce源碼解析--環(huán)形緩沖區(qū)

開發(fā) 開發(fā)工具
這篇文章把Map階段的環(huán)形緩沖區(qū)單獨(dú)拿出來進(jìn)行分析,對(duì)環(huán)形緩沖區(qū)的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)進(jìn)入環(huán)形緩沖區(qū)然后溢寫到磁盤的流程進(jìn)行分析。

這篇文章把Map階段的環(huán)形緩沖區(qū)單獨(dú)拿出來進(jìn)行分析,對(duì)環(huán)形緩沖區(qū)的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)進(jìn)入環(huán)形緩沖區(qū)然后溢寫到磁盤的流程進(jìn)行分析。

環(huán)形緩沖區(qū)數(shù)據(jù)結(jié)構(gòu)

Map過程中環(huán)形緩沖區(qū)是指數(shù)據(jù)被map處理之后會(huì)先放入內(nèi)存,內(nèi)存中的這片區(qū)域就是環(huán)形緩沖區(qū)。

環(huán)形緩沖區(qū)是在MapTask.MapOutputBuffer中定義的,相關(guān)的屬性如下:

  1. // k/v accounting 
  2. // 存放meta數(shù)據(jù)的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內(nèi)容的標(biāo)識(shí) 
  8. // meta數(shù)據(jù)和key value內(nèi)容都存放在同一個(gè)環(huán)形緩沖區(qū),所以需要分隔開 
  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數(shù)組,單位是byte,注意與kvmeta區(qū)分 
  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. // 一對(duì)key value的meta數(shù)據(jù)在kvmeta中占用的個(gè)數(shù) 
  27. private static final int NMETA = 4; // num meta ints 
  28. // 一對(duì)key value的meta數(shù)據(jù)在kvmeta中占用的byte數(shù) 
  29. private static final int METASIZE = NMETA * 4; // size in bytes 

環(huán)形緩沖區(qū)其實(shí)是一個(gè)數(shù)組,數(shù)組中存放著key、value的序列化數(shù)據(jù)和key、value的元數(shù)據(jù)信息,key/value的元數(shù)據(jù)存儲(chǔ)的格式是int類型,每個(gè)key/value對(duì)應(yīng)一個(gè)元數(shù)據(jù),元數(shù)據(jù)由4個(gè)int組成,第一個(gè)int存放value的起始位置,第二個(gè)存放key的起始位置,第三個(gè)存放partition,最后一個(gè)存放value的長度。

 

key/value序列化的數(shù)據(jù)和元數(shù)據(jù)在環(huán)形緩沖區(qū)中的存儲(chǔ)是由equator分隔的,key/value按照索引遞增的方向存儲(chǔ),meta則按照索引遞減的方向存儲(chǔ),將其數(shù)組抽象為一個(gè)環(huán)形結(jié)構(gòu)之后,以equator為界,key/value順時(shí)針存儲(chǔ),meta逆時(shí)針存儲(chǔ)。

初始化

 

環(huán)形緩沖區(qū)的結(jié)構(gòu)在MapOutputBuffer.init中創(chuàng)建。

  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的整數(shù)倍 
  12. final int sortmb = job.getInt(JobContext.IO_SORT_MB, 100); 
  13. // 所有的spill index 在內(nèi)存所占的大小的閾值 
  14. indexCacheMemoryLimit = job.getInt(JobContext.INDEX_CACHE_MEMORY_LIMIT, 
  15. INDEX_CACHE_MEMORY_LIMIT_DEFAULT); 
  16. ... 
  17. // 排序的實(shí)現(xiàn)類,可以自己實(shí)現(xiàn)。 這里用的是改寫的快排 
  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位將單位轉(zhuǎn)化為byte 
  22. int maxMemUsage = sortmb << 20
  23. // METASIZE是元數(shù)據(jù)的長度,元數(shù)據(jù)有4個(gè)int單元,分別為 
  24. // VALSTART、KEYSTART、PARTITION、VALLEN,而int為4個(gè)byte, 
  25. // 所以METASIZE長度為16。下面是計(jì)算buffer中最多有多少byte來存元數(shù)據(jù) 
  26. maxMemUsage -maxMemUsage % METASIZE; 
  27. // 元數(shù)據(jù)數(shù)組 以byte為單位 
  28. kvbuffer = new byte[maxMemUsage]; 
  29. bufvoid = kvbuffer.length; 
  30. // 將kvbuffer轉(zhuǎn)化為int型的kvmeta 以int為單位,也就是4byte 
  31. kvmeta = ByteBuffer.wrap(kvbuffer) 
  32. .order(ByteOrder.nativeOrder()) 
  33. .asIntBuffer(); 
  34. // 設(shè)置buf和kvmeta的分界線 
  35. setEquator(0); 
  36. bufstart = bufend = bufindex = equator
  37. kvstart = kvend = kvindex; 
  38. // kvmeta中存放元數(shù)據(jù)實(shí)體的最大個(gè)數(shù) 
  39. maxRec = kvmeta.capacity() / NMETA; 
  40. // buffer spill時(shí)的閾值(不單單是sortmb*spillper) 
  41. // 更加精確的是kvbuffer.length*spiller 
  42. softLimit = (int)(kvbuffer.length * spillper); 
  43. // 此變量較為重要,作為spill的動(dòng)態(tài)衡量標(biāo)準(zhǔn) 
  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時(shí),在有combiner的情況下,超過此閾值才執(zhí)行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是對(duì)環(huán)形緩沖區(qū)進(jìn)行初始化構(gòu)造,由mapreduce.task.io.sort.mb決定map中環(huán)形緩沖區(qū)的大小sortmb,默認(rèn)是100M。

此緩沖區(qū)也用于存放meta,一個(gè)meta占用METASIZE(16byte),則其中用于存放數(shù)據(jù)的大小是maxMemUsage -= sortmb << 20 % METASIZE(由此可知最好設(shè)置sortmb轉(zhuǎn)換為byte之后是16的整數(shù)倍),然后用maxMemUsage初始化kvbuffer字節(jié)數(shù)組和kvmeta整形數(shù)組,最后設(shè)置數(shù)組的一些標(biāo)識(shí)信息。利用setEquator(0)設(shè)置kvbuffer和kvmeta的分界線,初始化的時(shí)候以0為分界線,kvindex為aligned - METASIZE + kvbuffer.length,其位置在環(huán)形數(shù)組中相當(dāng)于按照逆時(shí)針方向減去METASIZE,由kvindex設(shè)置kvstart = kvend = kvindex,由equator設(shè)置bufstart = bufend = bufindex = equator,還得設(shè)置bufvoid = kvbuffer.length,bufvoid用于標(biāo)識(shí)用于存放數(shù)據(jù)的最大位置。

為了提高效率,當(dāng)buffer占用達(dá)到閾值之后,會(huì)進(jìn)行spill,這個(gè)閾值是由bufferRemaining進(jìn)行檢查的,bufferRemaining由softLimit = (int)(kvbuffer.length * spillper); bufferRemaining = softLimit;進(jìn)行初始化賦值,這里需要注意的是softLimit并不是sortmb*spillper,而是kvbuffer.length * spillper,當(dāng)sortmb << 20是16的整數(shù)倍時(shí),才可以認(rèn)為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. // 第一個(gè) entry的末尾位置,即元數(shù)據(jù)和kv數(shù)據(jù)的分界線 單位是byte 
  6. final int aligned = pos - (pos % METASIZE); 
  7. // Cast one of the operands to long to avoid integer overflow 
  8. // 元數(shù)據(jù)中存放數(shù)據(jù)的起始位置 
  9. kvindex = (int) 
  10. (((long)aligned - METASIZE + kvbuffer.length) % kvbuffer.length) / 4; 
  11. LOG.info("(EQUATOR) " + pos + " kvi " + kvindex + 
  12. "(" + (kvindex * 4) + ")"); 

buffer初始化之后的抽象數(shù)據(jù)結(jié)構(gòu)如下圖所示:

buffer初始化之后的抽象數(shù)據(jù)結(jié)構(gòu)

環(huán)形緩沖區(qū)數(shù)據(jù)結(jié)構(gòu)圖

寫入buffer

 

Map通過NewOutputCollector.write方法調(diào)用collector.collect向buffer中寫入數(shù)據(jù),數(shù)據(jù)寫入之前已在NewOutputCollector.write中對(duì)要寫入的數(shù)據(jù)進(jìn)行逐條分區(qū),下面看下collect

  1. // MapOutputBuffer.collect 
  2. public synchronized void collect(K key, V value, final int partition 
  3. ) throws IOException { 
  4. ... 
  5. // 新數(shù)據(jù)collect時(shí),先將剩余的空間減去元數(shù)據(jù)的長度,之后進(jìn)行判斷 
  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時(shí),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 及元數(shù)據(jù)信息寫入緩沖區(qū) 
  65. try { 
  66. // serialize key bytes into buffer 
  67. int keystart = bufindex
  68. // 將key序列化寫入kvbuffer中,并移動(dòng)bufindex 
  69. keySerializer.serialize(key); 
  70. // key所占空間被bufvoid分隔,則移動(dòng)key, 
  71. // 將其值放在連續(xù)的空間中便于sort時(shí)key的對(duì)比 
  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; 

每次寫入數(shù)據(jù)時(shí),執(zhí)行bufferRemaining -= METASIZE之后,檢查bufferRemaining,

 

如果大于0,直接將key/value序列化對(duì)和對(duì)應(yīng)的meta寫入buffer中,key/value是序列化之后寫入的,key/value經(jīng)過一些列的方法調(diào)用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)將數(shù)據(jù)寫入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,則將寫入的內(nèi)容分開存儲(chǔ),將一部分寫入bufindex和bufvoid之間,然后重置bufindex,將剩余的部分寫入,這里不區(qū)分key和value,寫入key之后會(huì)在collect中判斷bufindex < keystart,當(dāng)bufindex小時(shí),則key被分開存儲(chǔ),執(zhí)行bb.shiftBufferedKey(),value則直接寫入,不用判斷是否被分開存儲(chǔ),key不能分開存儲(chǔ)是因?yàn)橐獙?duì)key進(jìn)行排序。

這里需要注意的是要寫入的數(shù)據(jù)太長,并且kvinde==kvend,則拋出MapBufferTooSmallException異常,在collect中捕獲,將此數(shù)據(jù)直接spill到磁盤spillSingleRecord,也就是當(dāng)單條記錄過長時(shí),不寫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時(shí),判斷首部是否有足夠的空間存放key,有沒有足夠的空間,則先將首部的部分key寫入keytmp中,然后分兩次寫入,再次調(diào)用Buffer.write,如果有足夠的空間,分兩次copy,先將首部的部分key復(fù)制到headbytelen的位置,然后將末尾的部分key復(fù)制到首部,移動(dòng)bufindex,重置bufferRemaining的值。

key/value寫入之后,繼續(xù)寫入元數(shù)據(jù)信息并重置kvindex的值。

spill

 

一次寫入buffer結(jié)束,當(dāng)寫入數(shù)據(jù)比較多,bufferRemaining小于等于0時(shí),準(zhǔn)備進(jìn)行spill,首次spill,spillInProgress為false,此時(shí)查看bUsed = distanceTo(kvbidx, bufindex),此時(shí)bUsed >= softLimit 并且 (kvbend + METASIZE) % kvbuffer.length == equator - (equator % METASIZE),則進(jìn)行spill,調(diào)用startSpill

  1. private void startSpill() { 
  2. // 元數(shù)據(jù)的邊界賦值 
  3. kvend = (kvindex + NMETA) % kvmeta.capacity(); 
  4. // key/value的邊界賦值 
  5. bufend = bufmark
  6. // 設(shè)置spill運(yùn)行標(biāo)識(shí) 
  7. spillInProgress = true
  8. ... 
  9. // 利用重入鎖,對(duì)spill線程進(jìn)行喚醒 
  10. spillReady.signal(); 

startSpill喚醒spill線程之后,進(jìn)程spill操作,但此時(shí)map向buffer的寫入操作并沒有阻塞,需要重新邊界equator和bufferRemaining的值,先來看下equator和bufferRemaining值的設(shè)定:

  1. // 根據(jù)已經(jīng)寫入的kv得出每個(gè)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; 

因?yàn)閑quator是kvbuffer和kvmeta的分界線,為了更多的空間存儲(chǔ)kv,則最多拿出distkvi的一半來存儲(chǔ)meta,并且利用avgRec估算distkvi能存放多少個(gè)record和meta對(duì),根據(jù)record和meta對(duì)的個(gè)數(shù)估算meta所占空間的大小,從distkvi/2和meta所占空間的大小中取最小值,又因?yàn)閐istkvi中最少得存放一個(gè)meta,所占空間為METASIZE,在選取kvindex時(shí)需要求aligned,aligned最多為METASIZE-1,總和上述因素,最終選取equator為(bufindex + Math.max(2 * METASIZE - 1, Math.min(distkvi / 2, distkvi / (METASIZE + avgRec) * METASIZE)))。equator選取之后,設(shè)置bufmark = bufindex = newPos和kvindex,但此時(shí)并不設(shè)置bufstart、bufend和kvstart、kvend,因?yàn)檫@幾個(gè)值要用來表示spill數(shù)據(jù)的邊界。

spill之后,可用的空間減少了,則控制spill的bufferRemaining也應(yīng)該重新設(shè)置,bufferRemaining取三個(gè)值的最小值減去2*METASIZE,三個(gè)值分別是meta可用占用的空間distanceTo(bufend, newPos),kv可用空間distanceTo(newPos, serBound)和softLimit。這里為什么要減去2*METASIZE,一個(gè)是spill之前kvend到kvindex的距離,另一個(gè)是當(dāng)時(shí)的kvindex空間????此時(shí),已有一個(gè)record要寫入buffer,需要從bufferRemaining中減去當(dāng)前record的元數(shù)據(jù)占用的空間,即減去METASIZE,另一個(gè)METASIZE是在計(jì)算equator時(shí),沒有包括kvindex到kvend(spill之前)的這段METASIZE,所以要減去這個(gè)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. // 喚醒之后,進(jìn)行排序和溢寫到磁盤 
  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. // 用來存儲(chǔ)index文件 
  11. final SpillRecord spillRec = new SpillRecord(partitions); 
  12. // 創(chuàng)建寫入磁盤的spill文件 
  13. final Path filename = 
  14. mapOutputFile.getSpillFileForWrite(numSpills, size); 
  15. // 打開文件流 
  16. out = rfs.create(filename); 
  17. // kvend/4 是截止到當(dāng)前位置能存放多少個(gè)元數(shù)據(jù)實(shí)體 
  18. final int mstart = kvend / NMETA; 
  19. // kvstart 處能存放多少個(gè)元數(shù)據(jù)實(shí)體 
  20. // 元數(shù)據(jù)則在mstart和mend之間,(mstart - mend)則是元數(shù)據(jù)的個(gè)數(shù) 
  21. final int mend = 1 + // kvend is a valid record 
  22. (kvstart >= kvend 
  23. ? kvstart 
  24. : kvmeta.capacity() + kvstart) / NMETA; 
  25. // 排序 只對(duì)元數(shù)據(jù)進(jìn)行排序,只調(diào)整元數(shù)據(jù)在kvmeta中的順序 
  26. // 排序規(guī)則是MapOutputBuffer.compare, 
  27. // 先對(duì)partition進(jìn)行排序其次對(duì)key值排序 
  28. sorter.sort(MapOutputBuffer.this, mstart, mend, reporter); 
  29. int spindex = mstart
  30. // 創(chuàng)建rec,用于存放該分區(qū)在數(shù)據(jù)文件中的信息 
  31. final IndexRecord rec = new IndexRecord(); 
  32. final InMemValBytes value = new InMemValBytes(); 
  33. for (int i = 0; i < partitions; ++i) { 
  34. // 臨時(shí)文件是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. // 往磁盤寫數(shù)據(jù)時(shí)先判斷是否有combiner 
  42. if (combinerRunner == null) { 
  43. // spill directly 
  44. DataInputBuffer key = new DataInputBuffer(); 
  45. // 寫入相同partition的數(shù)據(jù) 
  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. // 記錄當(dāng)前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的信息,便于后續(xù)堆排序時(shí),取出partition相關(guān)的數(shù)據(jù)進(jìn)行排序 
  78. spillRec.putIndex(rec, i); 
  79.   
  80. writer = null
  81. } finally { 
  82. if (null != writer) writer.close(); 
  83. // 判斷內(nèi)存中的index文件是否超出閾值,超出則將index文件寫入磁盤 
  84. // 當(dāng)超出閾值時(shí)只是把當(dāng)前index和之后的index寫入磁盤 
  85. if (totalIndexCacheMemory >= indexCacheMemoryLimit) { 
  86. // create spill index file 
  87. // 創(chuàng)建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到磁盤,調(diào)用sorter.sort對(duì)meta進(jìn)行排序,先對(duì)partition進(jìn)行排序,然后按key排序,排序的結(jié)果只調(diào)整meta的順序。

排序之后,判斷是否有combiner,沒有則直接將record寫入磁盤,寫入時(shí)是一個(gè)partition一個(gè)IndexRecord,如果有combiner,則將該partition的record寫入kvIter,然后調(diào)用combinerRunner.combine執(zhí)行combiner。

寫入磁盤之后,將spillx.out對(duì)應(yīng)的spillRec放入內(nèi)存indexCacheList.add(spillRec),如果所占內(nèi)存totalIndexCacheMemory超過了indexCacheMemoryLimit,則創(chuàng)建index文件,將此次及以后的spillRec寫入index文件存入磁盤。

最后spill次數(shù)遞增。sortAndSpill結(jié)束之后,回到run方法中,執(zhí)行finally中的代碼,對(duì)kvstart和bufstart賦值,kvstart = kvend,bufstart = bufend,設(shè)置spillInProgress的狀態(tài)為false。

 

在spill的同時(shí),map往buffer的寫操作并沒有停止,依然在調(diào)用collect,再次回到collect方法中,

  1. // MapOutputBuffer.collect 
  2. public synchronized void collect(K key, V value, final int partition 
  3. ) throws IOException { 
  4. ... 
  5. // 新數(shù)據(jù)collect時(shí),先將剩余的空間減去元數(shù)據(jù)的長度,之后進(jìn)行判斷 
  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時(shí),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時(shí),判斷bufferRemaining -= METASIZE,此時(shí)的bufferRemaining是在開始spill時(shí)被重置過的(此時(shí)的bufferRemaining應(yīng)該比初始的softLimit要小),當(dāng)bufferRemaining小于等于0時(shí),進(jìn)入if,此時(shí)spillInProgress的狀態(tài)為false,進(jìn)入if (!spillInProgress),startSpill時(shí)對(duì)kvend和bufend進(jìn)行了重置,則此時(shí)(kvbend + METASIZE) % kvbuffer.length != equator - (equator % METASIZE),調(diào)用resetSpill(),將kvstart、kvend和bufstart、bufend設(shè)置為上次startSpill時(shí)的位置。此時(shí)buffer已將一部分內(nèi)容寫入磁盤,有大量空余的空間,則對(duì)bufferRemaining進(jìn)行重置,此次不spill。

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

 

最后一個(gè)METASIZE是當(dāng)前record進(jìn)入collect之后bufferRemaining減去的那個(gè)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) + ")"); 

當(dāng)bufferRemaining再次小于等于0時(shí),進(jìn)行spill,這以后就都是套路了。環(huán)形緩沖區(qū)分析到此結(jié)束。

【本文為51CTO專欄作者“王森豐”的原創(chuàng)稿件,轉(zhuǎn)載請(qǐng)注明出處】

戳這里,看該作者更多好文

責(zé)任編輯:趙寧寧 來源: 51CTO專欄
相關(guān)推薦

2023-10-09 23:01:09

MySQL數(shù)據(jù)庫

2021-06-26 07:50:20

STM32串口開發(fā)環(huán)形緩沖區(qū)

2011-12-14 16:30:42

javanio

2019-02-27 13:58:29

漏洞緩沖區(qū)溢出系統(tǒng)安全

2011-03-23 12:39:44

2018-11-01 08:31:05

2017-01-09 17:03:34

2011-03-23 11:35:00

2014-07-30 11:21:46

2009-11-16 17:26:17

Oracle優(yōu)化緩沖區(qū)

2009-11-16 17:08:59

Oracle日志緩沖區(qū)

2018-01-26 14:52:43

2009-11-16 16:59:24

Oracle優(yōu)化庫高速

2009-09-24 18:16:40

2009-07-15 15:50:48

Jython線程

2011-07-20 10:54:14

C++

2010-12-27 10:21:21

2022-05-07 08:27:42

緩沖區(qū)溢出堆棧

2010-10-09 14:45:48

2015-03-06 17:09:10

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)