Spark是现在很流行的一个基于内存的分布式计算框架,既然是基于内存,那么自然而然的,内存的管理就是Spark存储管理的重中之重了。那么,Spark究竟采用什么样的内存管理模型呢?本文就为大家揭开Spark内存管理模型的神秘面纱。

我们在《Spark源码分析之七:Task运行(一)》一文中曾经提到过,在Task被传递到Executor上去执行时,在为其分配的TaskRunner线程的run()方法内,在Task真正运行之前,我们就要构造一个任务内存管理器TaskMemoryManager,然后在反序列化Task对象的二进制数据得到Task对象后,需要将这个内存管理器TaskMemoryManager设置为Task的成员变量。那么,究竟TaskMemoryManager是如何被创建的呢?我们先看下TaskRunner线程的run()方法中涉及到的代码:

  1. // 获取任务内存管理器
  2. val taskMemoryManager = new TaskMemoryManager(env.memoryManager, taskId)

taskId好说,它就是Task的唯一标识ID,那么env.memoryManager呢,我们来看下SparkEnv的相关代码,如下所示:

  1. // 根据参数spark.memory.useLegacyMode确定使用哪种内存管理模型
  2. val useLegacyMemoryManager = conf.getBoolean("spark.memory.useLegacyMode", false)
  3. val memoryManager: MemoryManager =
  4. if (useLegacyMemoryManager) {// 如果还是采用之前的方式,则使用StaticMemoryManager内存管理模型,即静态内存管理模型
  5. new StaticMemoryManager(conf, numUsableCores)
  6. } else {// 否则,使用最新的UnifiedMemoryManager内存管理模型,即统一内存管理模型
  7. UnifiedMemoryManager(conf, numUsableCores)
  8. }

SparkEnv在构造过程中,会根据参数spark.memory.useLegacyMode来确定是否使用之前的内存管理模型,默认不采用之前的。如果是采用之前的,则memoryManager被实例化为一个StaticMemoryManager对象,否则采用新的内存管理模型,memoryManager被实例化为一个UnifiedMemoryManager内存对象。

我们知道,英文单词static代表静态、不变的意思,unified代表统一的意思。从字面意思来看,StaticMemoryManager表示是静态的内存管理器,何谓静态,就是按照某种算法确定内存的分配后,其整体分布不会随便改变,而UnifiedMemoryManager代表的是统一的内存管理器,统一么,是不是有共享和变动的意思。那么我们不妨大胆猜测下,StaticMemoryManager这种内存管理模型是在内存分配之初,即确定各区域内存的大小,并在Task运行过程中保持不变,而UnifiedMemoryManager则会根据Task运行过程中各区域数据对内存需要的程序进行动态调整。到底是不是这样呢?只有看过源码才能知晓。首先,我们看下StaticMemoryManager,通过SparkEnv中对其初始化的语句我们知道,它的初始化调用的是StaticMemoryManager的带有参数SparkConf类型的conf、Int类型的numCores的构造函数,代码如下:

  1. def this(conf: SparkConf, numCores: Int) {
  2. // 调用最底层的构造方法
  3. this(
  4. conf,
  5. // Execution区域(即运行区域,为shuffle使用)分配的可用内存总大小
  6. StaticMemoryManager.getMaxExecutionMemory(conf),
  7. // storage区域(即存储区域)分配的可用内存总大小
  8. StaticMemoryManager.getMaxStorageMemory(conf),
  9. numCores)
  10. }

其中,在调用最底层的构造方法之前,调用了伴生对象StaticMemoryManager的两个方法,分别是获取Execution区域(即运行区域,为shuffle使用)分配的可用内存总大小的getMaxExecutionMemory()和获取storage区域(即存储区域)分配的可用内存总大小的getMaxStorageMemory()方法。

何为Storage区域?何为Execution区域?这里,我们简单解释下,Storage就是存储的意思,它存储的是Task的运行结果等数据,当然前提是其运行结果比较小,足以在内存中盛放。那么Execution呢?执行的意思,通过参数中的shuffle,我猜测它实际上是shuffle过程中需要使用的内存数据(因为还未分析shuffle,这里只是猜测,猜错勿怪,还望读者指正)。

我们接着看下这两个方法,代码如下:

  1. /**
  2. * Return the total amount of memory available for the storage region, in bytes.
  3. * 返回为storage区域(即存储区域)分配的可用内存总大小,单位为bytes
  4. */
  5. private def getMaxStorageMemory(conf: SparkConf): Long = {
  6. // 系统可用最大内存,取参数spark.testing.memory,未配置的话取运行时环境中的最大内存
  7. val systemMaxMemory = conf.getLong("spark.testing.memory", Runtime.getRuntime.maxMemory)
  8. // 取storage区域(即存储区域)在总内存中所占比重,由参数spark.storage.memoryFraction确定,默认为0.6
  9. val memoryFraction = conf.getDouble("spark.storage.memoryFraction", 0.6)
  10. // 取storage区域(即存储区域)在系统为其可分配最大内存的安全系数,主要为了防止OOM,取参数spark.storage.safetyFraction,默认为0.9
  11. val safetyFraction = conf.getDouble("spark.storage.safetyFraction", 0.9)
  12. // 返回storage区域(即存储区域)分配的可用内存总大小,计算公式:系统可用最大内存 * 在系统可用最大内存中所占比重 * 安全系数
  13. (systemMaxMemory * memoryFraction * safetyFraction).toLong
  14. }
  15. /**
  16. * Return the total amount of memory available for the execution region, in bytes.
  17. * 返回为Execution区域(即运行区域,为shuffle使用)分配的可用内存总大小,单位为bytes
  18. */
  19. private def getMaxExecutionMemory(conf: SparkConf): Long = {
  20. // 系统可用最大内存,取参数spark.testing.memory,未配置的话取运行时环境中的最大内存
  21. val systemMaxMemory = conf.getLong("spark.testing.memory", Runtime.getRuntime.maxMemory)
  22. // 取Execution区域(即运行区域,为shuffle使用)在总内存中所占比重,由参数spark.shuffle.memoryFraction确定,默认为0.2
  23. val memoryFraction = conf.getDouble("spark.shuffle.memoryFraction", 0.2)
  24. // 取Execution区域(即运行区域,为shuffle使用)在系统为其可分配最大内存的安全系数,主要为了防止OOM,取参数spark.shuffle.safetyFraction,默认为0.8
  25. val safetyFraction = conf.getDouble("spark.shuffle.safetyFraction", 0.8)
  26. // 返回为Execution区域(即运行区域,为shuffle使用)分配的可用内存总大小,计算公式:系统可用最大内存 * 在系统可用最大内存中所占比重 * 安全系数
  27. (systemMaxMemory * memoryFraction * safetyFraction).toLong
  28. }

通过上述代码,我们可以看到,获取两个内存区域大小的方法是及其相似的,我们就以getMaxStorageMemory()方法为例,来详细说明。

首先,需要获得系统可用最大内存systemMaxMemory,取参数spark.testing.memory,未配置的话取运行时环境中的最大内存;

然后,需要获取取storage区域(即存储区域)在总内存中所占比重memoryFraction,由参数spark.storage.memoryFraction确定,默认为0.6;

接着,需要获取storage区域(即存储区域)在系统为其可分配最大内存的安全系数safetyFraction,主要为了防止OOM,取参数spark.storage.safetyFraction,默认为0.9;

最后,利用公式systemMaxMemory * memoryFraction * safetyFraction来计算出storage区域(即存储区域)分配的可用内存总大小。

前面几步都好说,默认情况下,storage区域(即存储区域)分配的可用内存总大小占系统可用内存大小的60%,那么最后为什么需要一个安全系数safetyFraction呢?设身处地的想一下,系统一开始分配它最大可用内存的60%给你,你上来就一下用完了,那么再有内存需求呢?是不是此时很容易就发生OOM呢?安全系统正式基于这个原因才设定的,也就是说,默认情况下,刚开始storage区域(即存储区域)分配的可用内存总大小占系统可用内存大小的54%,而不是60%。

getMaxExecutionMemory()方法与getMaxStorageMemory()方法处理逻辑一样,只不过取得参数不同罢了,默认情况下占系统可用最大内存的20%,而安全系数则是80%,故默认情况下,刚开始Execution区域(即运行区域,为shuffle使用)分配的可用内存总大小占系统可用内存大小的16%。

等等,好像少点什么?60%+20%=80%,不是100%!这是为什么呢?很简单,程序或者系统本身的运行,也是需要消耗内存的嘛!
        而StaticMemoryManager最底层的构造方法,也就是scala语言语法中类定义的部分,则是:

  1. private[spark] class StaticMemoryManager(
  2. conf: SparkConf,
  3. maxOnHeapExecutionMemory: Long,
  4. override val maxStorageMemory: Long,
  5. numCores: Int)
  6. extends MemoryManager(
  7. conf,
  8. numCores,
  9. maxStorageMemory,
  10. maxOnHeapExecutionMemory) {

我们看到,StaticMemoryManager静态内存管理器则持有了参数SparkConf类型的conf、Execution内存大小maxOnHeapExecutionMemory、Storage内存大小maxStorageMemory、CPU核数numCores等成员变量。

至此,StaticMemoryManager对象就初始化完毕。现在我们总结一下静态内存管理模型的特点,这种模型最大的一个缺点就是每种区域不能超过参数为其配置的最大值,即便是一种区域的内存很繁忙,而另外一种很空闲,也不能超过上限占用更多的内存,即使是总数未超过规定的阈值。那么,随之而来的一种解决方案便是UnifiedMemoryManager,统一的内存管理模型。

接下来,我们再看下UnifiedMemoryManager,即统一内存管理器。在SparkEnv中,它是通过如下方式完成初始化的:

  1. UnifiedMemoryManager(conf, numUsableCores)

读者这里可能有疑问了,为什么没有new关键字呢?这正是scala语言的特点。它其实是通过UnifiedMemoryManager类的apply()方法完成初始化的。代码如下:

  1. def apply(conf: SparkConf, numCores: Int): UnifiedMemoryManager = {
  2. // 获得execution和storage区域共享的最大内存
  3. val maxMemory = getMaxMemory(conf)
  4. // 构造UnifiedMemoryManager对象,
  5. new UnifiedMemoryManager(
  6. conf,
  7. maxMemory = maxMemory,
  8. // storage区域内存大小初始为execution和storage区域共享的最大内存的spark.memory.storageFraction,默认为0.5,即一半
  9. storageRegionSize =
  10. (maxMemory * conf.getDouble("spark.memory.storageFraction", 0.5)).toLong,
  11. numCores = numCores)
  12. }

首先,需要获得execution和storage区域共享的最大内存maxMemory;

然后,构造UnifiedMemoryManager对象,而storage区域内存大小storageRegionSize则初始化为execution和storage区域共享的最大内存maxMemory的spark.memory.storageFraction,默认为0.5,即一半。

下面,我们主要看下获得execution和storage区域共享的最大内存的getMaxMemory()方法。代码如下:

  1. /**
  2. * Return the total amount of memory shared between execution and storage, in bytes.
  3. * 返回execution和storage区域共享的最大内存
  4. */
  5. private def getMaxMemory(conf: SparkConf): Long = {
  6. // 获取系统可用最大内存systemMemory,取参数spark.testing.memory,未配置的话取运行时环境中的最大内存
  7. val systemMemory = conf.getLong("spark.testing.memory", Runtime.getRuntime.maxMemory)
  8. // 获取预留内存reservedMemory,取参数spark.testing.reservedMemory,
  9. // 未配置的话,根据参数spark.testing来确定默认值,参数spark.testing存在的话,默认为0,否则默认为300M
  10. val reservedMemory = conf.getLong("spark.testing.reservedMemory",
  11. if (conf.contains("spark.testing")) 0 else RESERVED_SYSTEM_MEMORY_BYTES)
  12. // 取最小的系统内存minSystemMemory,为预留内存reservedMemory的1.5倍
  13. val minSystemMemory = reservedMemory * 1.5
  14. // 如果系统可用最大内存systemMemory小于最小的系统内存minSystemMemory,即预留内存reservedMemory的1.5倍的话,抛出异常
  15. // 提醒用户调大JVM堆大小
  16. if (systemMemory < minSystemMemory) {
  17. throw new IllegalArgumentException(s"System memory $systemMemory must " +
  18. s"be at least $minSystemMemory. Please use a larger heap size.")
  19. }
  20. // 计算可用内存usableMemory,即系统最大可用内存systemMemory减去预留内存reservedMemory
  21. val usableMemory = systemMemory - reservedMemory
  22. // 取可用内存所占比重,即参数spark.memory.fraction,默认为0.75
  23. val memoryFraction = conf.getDouble("spark.memory.fraction", 0.75)
  24. // 返回的execution和storage区域共享的最大内存为usableMemory * memoryFraction
  25. (usableMemory * memoryFraction).toLong
  26. }

处理流程大体如下:

1、获取系统可用最大内存systemMemory,取参数spark.testing.memory,未配置的话取运行时环境中的最大内存;

2、获取预留内存reservedMemory,取参数spark.testing.reservedMemory,未配置的话,根据参数spark.testing来确定默认值,参数spark.testing存在的话,默认为0,否则默认为300M;

3、取最小的系统内存minSystemMemory,为预留内存reservedMemory的1.5倍;

4、如果系统可用最大内存systemMemory小于最小的系统内存minSystemMemory,即预留内存reservedMemory的1.5倍的话,抛出异常,提醒用户调大JVM堆大小;

5、计算可用内存usableMemory,即系统最大可用内存systemMemory减去预留内存reservedMemory;

6、取可用内存所占比重,即参数spark.memory.fraction,默认为0.75;

7、返回的execution和storage区域共享的最大内存为usableMemory * memoryFraction。

也就是说,UnifiedMemoryManager统一内存存储管理策略中,默认情况下,storage区域和execution区域默认都占其共享内存区域的一半,而execution和storage区域共享的最大内存为系统最大可用内存systemMemory减去预留内存reservedMemory后的75%。至于在哪里体现的动态调整,则要到真正申请内存时再体现了。

好了,UnifiedMemoryManager统一内存存储管理器的初始化也讲完了。那么,接下来的问题则是,何时以及如何进行内存的申请及分配?针对storage和execution,我们一个个的看。

首先看看storage,顾名思义,storage是存储的意思,也就是说是在Task运行完成出结果后,对结果的存储区域。我们回顾下博文《Spark源码分析之七:Task运行(一)》中所讲的Task运行完成后对Task运行结果的处理,如果 Task运行结果大小超过Akka除去需要保留的字节外最大大小,则将结果写入BlockManager,那么是如何写入的呢?代码如下:

  1. env.blockManager.putBytes(
  2. blockId, serializedDirectResult, StorageLevel.MEMORY_AND_DISK_SER)

调用的是BlockManager的putBytes()方法,很显然,写入的是二进制Bytes数据,且使用的存储策略是MEMORY_AND_DISK_SER。我们先看下这个方法:

  1. /**
  2. * Put a new block of serialized bytes to the block manager.
  3. * Return a list of blocks updated as a result of this put.
  4. */
  5. def putBytes(
  6. blockId: BlockId,
  7. bytes: ByteBuffer,
  8. level: StorageLevel,
  9. tellMaster: Boolean = true,
  10. effectiveStorageLevel: Option[StorageLevel] = None): Seq[(BlockId, BlockStatus)] = {
  11. require(bytes != null, "Bytes is null")
  12. doPut(blockId, ByteBufferValues(bytes), level, tellMaster, effectiveStorageLevel)
  13. }

调用的是doPut()方法,传入的是ByteBufferValues类型的数据,而doPut()方法中,则有如下关键代码:

  1. // Actually put the values
  2. val result = data match {
  3. case IteratorValues(iterator) =>
  4. blockStore.putIterator(blockId, iterator, putLevel, returnValues)
  5. case ArrayValues(array) =>
  6. blockStore.putArray(blockId, array, putLevel, returnValues)
  7. case ByteBufferValues(bytes) =>
  8. bytes.rewind()
  9. blockStore.putBytes(blockId, bytes, putLevel)
  10. }

上面提到过,传入的是ByteBufferValues类型的数据,那么这里调用的就应该是BlockStore的putBytes()方法。而BlockStore是一个抽象类,有硬盘DiskStore、外部块ExternalBlockStore、内存MemoryStore三种实现形式,这里既然讲的是内存管理模型,我们当然要看其内存实现形式MemoryStore了。而putBytes()方法中,不管level.deserialized是true还是false,最终还是调用的tryToPut()方法,该方法中,对内存的处理为:

  1. val enoughMemory = memoryManager.acquireStorageMemory(blockId, size, droppedBlocks)
  2. if (enoughMemory) {
  3. // We acquired enough memory for the block, so go ahead and put it
  4. val entry = new MemoryEntry(value(), size, deserialized)
  5. entries.synchronized {
  6. entries.put(blockId, entry)
  7. }
  8. val valuesOrBytes = if (deserialized) "values" else "bytes"
  9. logInfo("Block %s stored as %s in memory (estimated size %s, free %s)".format(
  10. blockId, valuesOrBytes, Utils.bytesToString(size), Utils.bytesToString(blocksMemoryUsed)))
  11. } else {
  12. // Tell the block manager that we couldn't put it in memory so that it can drop it to
  13. // disk if the block allows disk storage.
  14. lazy val data = if (deserialized) {
  15. Left(value().asInstanceOf[Array[Any]])
  16. } else {
  17. Right(value().asInstanceOf[ByteBuffer].duplicate())
  18. }
  19. val droppedBlockStatus = blockManager.dropFromMemory(blockId, () => data)
  20. droppedBlockStatus.foreach { status => droppedBlocks += ((blockId, status)) }
  21. }

由上面我们可以得知,是通过memoryManager的acquireStorageMemory()方法来查看是否存在足够内存的。我们就先看下StaticMemoryManager的acquireStorageMemory()方法,定义如下:

  1. override def acquireStorageMemory(
  2. blockId: BlockId,
  3. numBytes: Long,
  4. evictedBlocks: mutable.Buffer[(BlockId, BlockStatus)]): Boolean = synchronized {
  5. if (numBytes > maxStorageMemory) {// 如果需要的大小numBytes超过Storage区域内存的上限,直接返回false,说明内存不够
  6. // Fail fast if the block simply won't fit
  7. logInfo(s"Will not store $blockId as the required space ($numBytes bytes) exceeds our " +
  8. s"memory limit ($maxStorageMemory bytes)")
  9. false
  10. } else {// 否则,调用storageMemoryPool的acquireMemory()方法,申请内存
  11. storageMemoryPool.acquireMemory(blockId, numBytes, evictedBlocks)
  12. }
  13. }

对了,就是这么简单。如果需要申请的内存超过Storage区域内存最大值的上限,则表明没有足够的内存进行存储,否则,调用storageMemoryPool的acquireMemory()方法分配内存,正是这里体现了static一词。至于具体分配内存的storageMemoryPool,我们放到最后和Execution区域时的onHeapExecutionMemoryPool、offHeapExecutionMemoryPool一起讲,这里先了解下它的概念即可,它实际上是对应某种区域的内存池,是对内存总大小、可用内存、已用内存等内存使用情况的一种记账的专用对象。

我们再看下UnifiedMemoryManager,其acquireStorageMemory()方法如下:

  1. override def acquireStorageMemory(
  2. blockId: BlockId,
  3. numBytes: Long,
  4. evictedBlocks: mutable.Buffer[(BlockId, BlockStatus)]): Boolean = synchronized {
  5. assert(onHeapExecutionMemoryPool.poolSize + storageMemoryPool.poolSize == maxMemory)
  6. assert(numBytes >= 0)
  7. // 如果需要申请的内存大小超过maxStorageMemory,即execution和storage区域共享的最大内存减去Execution已用内存,快速返回,
  8. // 这里是将execution和storage区域一起考虑的
  9. if (numBytes > maxStorageMemory) {
  10. // Fail fast if the block simply won't fit
  11. logInfo(s"Will not store $blockId as the required space ($numBytes bytes) exceeds our " +
  12. s"memory limit ($maxStorageMemory bytes)")
  13. return false
  14. }
  15. // 如果需要申请的内存大小超过预分配storage区域中可用大小memoryFree
  16. if (numBytes > storageMemoryPool.memoryFree) {
  17. // There is not enough free memory in the storage pool, so try to borrow free memory from
  18. // the execution pool.
  19. // 从Execution区域借调的内存大小,为需要申请内存大小和预分配的Execution区域可用大小memoryFree的较小者
  20. val memoryBorrowedFromExecution = Math.min(onHeapExecutionMemoryPool.memoryFree, numBytes)
  21. // Execution区域减小相应的值
  22. onHeapExecutionMemoryPool.decrementPoolSize(memoryBorrowedFromExecution)
  23. // Storage区域增大相应的值
  24. storageMemoryPool.incrementPoolSize(memoryBorrowedFromExecution)
  25. }
  26. // 通过storageMemoryPool完成内存分配
  27. storageMemoryPool.acquireMemory(blockId, numBytes, evictedBlocks)
  28. }

首先,我们需要先了解下maxStorageMemory,这个和StaticMemoryManager中不一样,后者为按照比例和安全系数预分配的固定不变的大小,而这里则是通过如下方式定义的:

  1. // maxStorageMemory为execution和storage区域共享的最大内存减去Execution已用内存
  2. override def maxStorageMemory: Long = synchronized {
  3. maxMemory - onHeapExecutionMemoryPool.memoryUsed
  4. }

这个maxStorageMemory为execution和storage区域共享的最大内存减去Execution已用内存。好了,继续分析吧!

首先,如果需要申请的内存大小超过maxStorageMemory,即execution和storage区域共享的最大内存减去Execution已用内存,快速返回false,表示内存不充足不可用,这里是将execution和storage区域一起考虑的;

然后,如果需要申请的内存大小超过预分配storage区域中可用大小memoryFree,计算可以从从Execution区域借调的内存大小,该大小为需要申请内存大小和预分配的Execution区域可用大小memoryFree的较小者,然后Execution区域减小相应的值,Storage区域增大相应的值,完成动态调整;

最后,通过storageMemoryPool完成内存分配。

至此,StaticMemoryManager和UnifiedMemoryManager中,storage区域内存何时申请及如何分配我们已经讲完了。

接下来看看Execution区域。它申请内存的触发时机是在何时呢?之前,我们已经提到过它是被shuffle使用的,对于shuffle的详细细节,在这里,读者大可不必深究,我们会在专门的shuffle模块中进行讲解。通过代码追溯,我们可以大体了解到,它在ShuffleExternalSorter的insertRecord()方法,而ShuffleExternalSorter是一个专业的外部分类器,负责将传入的记录追加到数据页中。当所有的记录被插入,或者当前线程的shuffle内存已达上限时,内存中的记录就会通过它们的分区ID进行排序。

我们来看下它的insertRecord()方法,该方法负责将记录Record插入到数据页中,代码如下:

  1. /**
  2. * Write a record to the shuffle sorter.
  3. */
  4. public void insertRecord(Object recordBase, long recordOffset, int length, int partitionId)
  5. throws IOException {
  6. // for tests
  7. assert(inMemSorter != null);
  8. if (inMemSorter.numRecords() > numElementsForSpillThreshold) {
  9. spill();
  10. }
  11. growPointerArrayIfNecessary();
  12. // Need 4 bytes to store the record length.
  13. final int required = length + 4;
  14. acquireNewPageIfNecessary(required);
  15. assert(currentPage != null);
  16. final Object base = currentPage.getBaseObject();
  17. final long recordAddress = taskMemoryManager.encodePageNumberAndOffset(currentPage, pageCursor);
  18. Platform.putInt(base, pageCursor, length);
  19. pageCursor += 4;
  20. Platform.copyMemory(recordBase, recordOffset, base, pageCursor, length);
  21. pageCursor += length;
  22. inMemSorter.insertRecord(recordAddress, partitionId);
  23. }

可以看到,在方法处理逻辑中,会调用acquireNewPageIfNecessary()方法,该方法的作用就是为了插入一条额外的记录,在必要的情况下申请更多的内存。它的实现如下:

  1. private void acquireNewPageIfNecessary(int required) {
  2. if (currentPage == null ||
  3. pageCursor + required > currentPage.getBaseOffset() + currentPage.size() ) {
  4. // TODO: try to find space in previous pages
  5. currentPage = allocatePage(required);
  6. pageCursor = currentPage.getBaseOffset();
  7. allocatedPages.add(currentPage);
  8. }
  9. }

它会调用allocatePage()方法,继续追踪,在其父类MemoryConsumer中,代码如下:

  1. /**
  2. * Allocate a memory block with at least `required` bytes.
  3. *
  4. * Throws IOException if there is not enough memory.
  5. *
  6. * @throws OutOfMemoryError
  7. */
  8. protected MemoryBlock allocatePage(long required) {
  9. MemoryBlock page = taskMemoryManager.allocatePage(Math.max(pageSize, required), this);
  10. if (page == null || page.size() < required) {
  11. long got = 0;
  12. if (page != null) {
  13. got = page.size();
  14. taskMemoryManager.freePage(page, this);
  15. }
  16. taskMemoryManager.showMemoryUsage();
  17. throw new OutOfMemoryError("Unable to acquire " + required + " bytes of memory, got " + got);
  18. }
  19. used += page.size();
  20. return page;
  21. }

继而会调用TaskMemoryManager的allocatePage()方法,我们继续看TaskMemoryManager的allocatePage()方法,发现它会调用acquireExecutionMemory()方法,而acquireExecutionMemory()方法则会调用MemoryManager的同名方法,于是,Execution区域内存分配最终就落在了MemoryManager的acquireExecutionMemory()方法上了。

仿照上面的storage区域的分析,我们还是分Static和Unified两种方式来讲解。先看Static,其acquireExecutionMemory()方法实现如下:

  1. private[memory]
  2. override def acquireExecutionMemory(
  3. numBytes: Long,
  4. taskAttemptId: Long,
  5. memoryMode: MemoryMode): Long = synchronized {
  6. // 根据MemoryMode的种类决定如何分配内存
  7. memoryMode match {
  8. // 如果是堆内,即ON_HEAP,则通过onHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配
  9. case MemoryMode.ON_HEAP => onHeapExecutionMemoryPool.acquireMemory(numBytes, taskAttemptId)
  10. // 如果是堆外,即OFF_HEAP,则通过offHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配
  11. case MemoryMode.OFF_HEAP => offHeapExecutionMemoryPool.acquireMemory(numBytes, taskAttemptId)
  12. }
  13. }
  14. }

这个方法的逻辑很简单,根据MemoryMode的种类来决定如何分配Execution区域内存。如果是堆内,即ON_HEAP,则通过onHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配;如果是堆外,即OFF_HEAP,则通过offHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配。

现在再看下UnifiedMemoryManager的acquireExecutionMemory()方法,代码如下:

  1. /**
  2. * Try to acquire up to `numBytes` of execution memory for the current task and return the
  3. * number of bytes obtained, or 0 if none can be allocated.
  4. *
  5. * This call may block until there is enough free memory in some situations, to make sure each
  6. * task has a chance to ramp up to at least 1 / 2N of the total memory pool (where N is the # of
  7. * active tasks) before it is forced to spill. This can happen if the number of tasks increase
  8. * but an older task had a lot of memory already.
  9. */
  10. override private[memory] def acquireExecutionMemory(
  11. numBytes: Long,
  12. taskAttemptId: Long,
  13. memoryMode: MemoryMode): Long = synchronized {
  14. // 确保onHeapExecutionMemoryPool和storageMemoryPool大小之和等于二者共享内存区域maxMemory大小
  15. assert(onHeapExecutionMemoryPool.poolSize + storageMemoryPool.poolSize == maxMemory)
  16. assert(numBytes >= 0)
  17. memoryMode match {
  18. // 如果是堆内,即ON_HEAP,则通过onHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配
  19. case MemoryMode.ON_HEAP =>
  20. /**
  21. * 通过收回缓存的块扩充the execution pool,从而减少the storage pool。
  22. * Grow the execution pool by evicting cached blocks, thereby shrinking the storage pool.
  23. *
  24. * When acquiring memory for a task, the execution pool may need to make multiple
  25. * attempts. Each attempt must be able to evict storage in case another task jumps in
  26. * and caches a large block between the attempts. This is called once per attempt.
  27. */
  28. def maybeGrowExecutionPool(extraMemoryNeeded: Long): Unit = {
  29. // 如果需要额外的内存,即Execution预分配的内存已不够使用
  30. if (extraMemoryNeeded > 0) {
  31. // There is not enough free memory in the execution pool, so try to reclaim memory from
  32. // storage. We can reclaim any free memory from the storage pool. If the storage pool
  33. // has grown to become larger than `storageRegionSize`, we can evict blocks and reclaim
  34. // the memory that storage has borrowed from execution.
  35. // 此时,在the execution pool中已不存在足够的可用内存,所以我们尝试从storage区域回收部分内存。
  36. // 我们可以回收the storage pool中的全部可用内存。
  37. // 如果the storage pool逐渐增大至大于storageRegionSize,即初始化时storage区域的最大内存,
  38. // 我们可以回收部分blocks,并回收storage区域从execution借用的那些内存。
  39. // 首先取storageMemoryPool可用内存、storageMemoryPool总内存减去初始化时内存的较大者memoryReclaimableFromStorage
  40. // 意思也就是,一定会把storageMemoryPool的可用内存全部借给execution区域,并且如果当前storageMemoryPool大小比初始化时大了,且大的程度比当前可用内存还大,则回收部分内存
  41. val memoryReclaimableFromStorage =
  42. math.max(storageMemoryPool.memoryFree, storageMemoryPool.poolSize - storageRegionSize)
  43. //
  44. if (memoryReclaimableFromStorage > 0) {
  45. // Only reclaim as much space as is necessary and available:
  46. // 仅仅回收可用及必需的内存
  47. // storageMemoryPool调用shrinkPoolToFreeSpace方法回收并减持部分内存spaceReclaimed
  48. val spaceReclaimed = storageMemoryPool.shrinkPoolToFreeSpace(
  49. math.min(extraMemoryNeeded, memoryReclaimableFromStorage))
  50. // onHeapExecutionMemoryPool增持相应的onHeapExecutionMemoryPool内存
  51. onHeapExecutionMemoryPool.incrementPoolSize(spaceReclaimed)
  52. }
  53. }
  54. }
  55. /**
  56. * The size the execution pool would have after evicting storage memory.
  57. *
  58. * The execution memory pool divides this quantity among the active tasks evenly to cap
  59. * the execution memory allocation for each task. It is important to keep this greater
  60. * than the execution pool size, which doesn't take into account potential memory that
  61. * could be freed by evicting storage. Otherwise we may hit SPARK-12155.
  62. *
  63. * Additionally, this quantity should be kept below `maxMemory` to arbitrate fairness
  64. * in execution memory allocation across tasks, Otherwise, a task may occupy more than
  65. * its fair share of execution memory, mistakenly thinking that other tasks can acquire
  66. * the portion of storage memory that cannot be evicted.
  67. */
  68. // 计算ExecutionPool的最大大小
  69. def computeMaxExecutionPoolSize(): Long = {
  70. // storage区域和Execution区域二者共享内存减去storage区域已使用内存和storage区域初始化大小
  71. maxMemory - math.min(storageMemoryUsed, storageRegionSize)
  72. }
  73. onHeapExecutionMemoryPool.acquireMemory(
  74. numBytes, taskAttemptId, maybeGrowExecutionPool, computeMaxExecutionPoolSize)
  75. // 如果是堆外,即OFF_HEAP,则通过offHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配
  76. case MemoryMode.OFF_HEAP =>
  77. // For now, we only support on-heap caching of data, so we do not need to interact with
  78. // the storage pool when allocating off-heap memory. This will change in the future, though.
  79. offHeapExecutionMemoryPool.acquireMemory(numBytes, taskAttemptId)
  80. }
  81. }

UnifiedMemoryManager同样也是区别ON_HEAP和OFF_HEAP两种方式来进行Execution区域内存的分配,OFF_HEAP方式和StaticMemoryManager一样,也是通过offHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配,ON_HEAP则要稍微复杂些,它虽然也是和StaticMemoryManager一样通过onHeapExecutionMemoryPool的acquireMemory对Task进行Execution区域内存分配,但是它的分配有种特殊情况,即如果the execution pool可用内存不够,即如果需要额外的内存,会尝试从storage区域回收部分内存。此时,可以回收the storage pool中的全部可用内存,如果the storage pool逐渐增大至大于storageRegionSize,即初始化时storage区域的最大内存,我们可以回收部分blocks,并回收storage区域从execution借用的那些内存。

我们来看maybeGrowExecutionPool()方法的代码逻辑:如果需要额外的内存,即Execution预分配的内存已不够使用,首先取storageMemoryPool可用内存、storageMemoryPool总内存减去初始化时内存的较大者memoryReclaimableFromStorage,意思也就是,一定会把storageMemoryPool的可用内存全部借给execution区域,并且如果当前storageMemoryPool大小比初始化时大了,且大的程度比当前可用内存还大,则回收部分内存,然后storageMemoryPool调用shrinkPoolToFreeSpace方法回收并减持部分内存spaceReclaimed,onHeapExecutionMemoryPool增持相应的spaceReclaimed内存,起到了一个动态调整和此消彼长的效果。

最后,我们来看下实际分配内存的storageMemoryPool、onHeapExecutionMemoryPool以及offHeapExecutionMemoryPool。它们的定义在MemoryManager中,代码如下:

  1. @GuardedBy("this")
  2. protected val storageMemoryPool = new StorageMemoryPool(this)
  3. @GuardedBy("this")
  4. protected val onHeapExecutionMemoryPool = new ExecutionMemoryPool(this, "on-heap execution")
  5. @GuardedBy("this")
  6. protected val offHeapExecutionMemoryPool = new ExecutionMemoryPool(this, "off-heap execution")

它们的类型分别是StorageMemoryPool、ExecutionMemoryPool,只不过后两者是用两个名称不同的对象来分别提供内存服务的,二者的名称分别是on-heap execution和off-heap execution。而它们共同继承自抽象类MemoryPool,我们先看下MemoryPool的代码:

  1. /**
  2. * Manages bookkeeping for an adjustable-sized region of memory. This class is internal to
  3. * the [[MemoryManager]]. See subclasses for more details.
  4. * 为一个可调整大小的内存区域管理记账工作。这个类在MemoryManager类中使用。更多详情请查看实现子类。
  5. *
  6. * @param lock a [[MemoryManager]] instance, used for synchronization. We purposely erase the type
  7. *             to `Object` to avoid programming errors, since this object should only be used for
  8. *             synchronization purposes.
  9. */
  10. private[memory] abstract class MemoryPool(lock: Object) {
  11. @GuardedBy("lock")
  12. // 内存池的大小
  13. private[this] var _poolSize: Long = 0
  14. /**
  15. * Returns the current size of the pool, in bytes.
  16. * 获取内存池大小,需要使用对象lock的同步关键字synchronized,解决并发的问题,
  17. * 而这个lock就是StaticMemoryManager或UnifiedMemoryManager类类型的对象
  18. */
  19. final def poolSize: Long = lock.synchronized {
  20. _poolSize
  21. }
  22. /**
  23. * Returns the amount of free memory in the pool, in bytes.
  24. * 返回内存池可用内存,即内存池总大小减去已用内存,同样需要使用lock的同步关键字synchronized,解决并发的问题
  25. */
  26. final def memoryFree: Long = lock.synchronized {
  27. _poolSize - memoryUsed
  28. }
  29. /**
  30. * Expands the pool by `delta` bytes.
  31. * 对内存池进行delta bytes的扩充,即完成_poolSize += delta,delta必须大于等于0
  32. */
  33. final def incrementPoolSize(delta: Long): Unit = lock.synchronized {
  34. require(delta >= 0)
  35. _poolSize += delta
  36. }
  37. /**
  38. * Shrinks the pool by `delta` bytes.
  39. * 对内存池进行delta字节的收缩,即_poolSize -= delta,delta必须大于等于0,且小于内存池现在的大小,并且必须小于等于内存池现在可用大小
  40. */
  41. final def decrementPoolSize(delta: Long): Unit = lock.synchronized {
  42. require(delta >= 0)
  43. require(delta <= _poolSize)
  44. require(_poolSize - delta >= memoryUsed)
  45. _poolSize -= delta
  46. }
  47. /**
  48. * Returns the amount of used memory in this pool (in bytes).
  49. * 返回内存池现在已使用的大小,由子类实现
  50. */
  51. def memoryUsed: Long
  52. }

很简单,一切尽在代码注释中,读者可自行补脑。

下面,我们看下StorageMemoryPool的实现,代码如下:

  1. /**
  2. * Performs bookkeeping for managing an adjustable-size pool of memory that is used for storage
  3. * (caching).
  4. * 完成为管理一个可调整大小的用于存储(caching)的内存池的记账工作。
  5. *
  6. * @param lock a [[MemoryManager]] instance to synchronize on
  7. */
  8. private[memory] class StorageMemoryPool(lock: Object) extends MemoryPool(lock) with Logging {
  9. @GuardedBy("lock")
  10. // 已使用内存大小
  11. private[this] var _memoryUsed: Long = 0L
  12. // 获取已使用内存大小memoryUsed,需要使用对象lock的同步关键字synchronized,解决并发的问题,
  13. // 而这个lock就是StaticMemoryManager或UnifiedMemoryManager类类型的对象
  14. override def memoryUsed: Long = lock.synchronized {
  15. _memoryUsed
  16. }
  17. // MemoryStore内存存储
  18. private var _memoryStore: MemoryStore = _
  19. def memoryStore: MemoryStore = {
  20. if (_memoryStore == null) {
  21. throw new IllegalStateException("memory store not initialized yet")
  22. }
  23. _memoryStore
  24. }
  25. /**
  26. * Set the [[MemoryStore]] used by this manager to evict cached blocks.
  27. * This must be set after construction due to initialization ordering constraints.
  28. */
  29. final def setMemoryStore(store: MemoryStore): Unit = {
  30. _memoryStore = store
  31. }
  32. /**
  33. * Acquire N bytes of memory to cache the given block, evicting existing ones if necessary.
  34. * Blocks evicted in the process, if any, are added to `evictedBlocks`.
  35. * @return whether all N bytes were successfully granted.
  36. * 申请内存
  37. */
  38. def acquireMemory(
  39. blockId: BlockId,
  40. numBytes: Long,
  41. evictedBlocks: mutable.Buffer[(BlockId, BlockStatus)]): Boolean =
  42. // 需要lock的synchronized,解决并发的问题
  43. lock.synchronized {
  44. // 需要释放的资源,为需要申请的大小减去内存池目前可用内存大小
  45. val numBytesToFree = math.max(0, numBytes - memoryFree)
  46. // 调用同名方法acquireMemory()
  47. acquireMemory(blockId, numBytes, numBytesToFree, evictedBlocks)
  48. }
  49. /**
  50. * Acquire N bytes of storage memory for the given block, evicting existing ones if necessary.
  51. *
  52. * @param blockId the ID of the block we are acquiring storage memory for
  53. * @param numBytesToAcquire the size of this block
  54. * @param numBytesToFree the amount of space to be freed through evicting blocks
  55. * @return whether all N bytes were successfully granted.
  56. */
  57. def acquireMemory(
  58. blockId: BlockId,
  59. numBytesToAcquire: Long,
  60. numBytesToFree: Long,
  61. evictedBlocks: mutable.Buffer[(BlockId, BlockStatus)]): Boolean = lock.synchronized {
  62. // 申请分配的内存必须大于等于0
  63. assert(numBytesToAcquire >= 0)
  64. // 需要释放的内存必须大于等于0
  65. assert(numBytesToFree >= 0)
  66. // 已使用内存必须小于等于内存池大小
  67. assert(memoryUsed <= poolSize)
  68. if (numBytesToFree > 0) {
  69. // 调用MemoryStore的evictBlocksToFreeSpace()方法释放numBytesToFree大小内存
  70. memoryStore.evictBlocksToFreeSpace(Some(blockId), numBytesToFree, evictedBlocks)
  71. // Register evicted blocks, if any, with the active task metrics
  72. Option(TaskContext.get()).foreach { tc =>
  73. val metrics = tc.taskMetrics()
  74. val lastUpdatedBlocks = metrics.updatedBlocks.getOrElse(Seq[(BlockId, BlockStatus)]())
  75. metrics.updatedBlocks = Some(lastUpdatedBlocks ++ evictedBlocks.toSeq)
  76. }
  77. }
  78. // NOTE: If the memory store evicts blocks, then those evictions will synchronously call
  79. // back into this StorageMemoryPool in order to free memory. Therefore, these variables
  80. // should have been updated.
  81. // 判断是否有足够的内存,即申请分配的内存必须小于等于可用内存
  82. val enoughMemory = numBytesToAcquire <= memoryFree
  83. if (enoughMemory) {
  84. // 如果有足够的内存,已使用内存_memoryUsed增加numBytesToAcquire
  85. _memoryUsed += numBytesToAcquire
  86. }
  87. // 返回enoughMemory,标志内存是否分配成功,即存在可用内存的话就分配成功,否则分配不成功
  88. enoughMemory
  89. }
  90. // 释放size大小的内存,同样需要lock对象上的synchronized关键字,解决并发问题
  91. def releaseMemory(size: Long): Unit = lock.synchronized {
  92. // 如果size大于目前已使用内存_memoryUsed,记录Warning日志信息,且已使用内存_memoryUsed设置为0
  93. if (size > _memoryUsed) {
  94. logWarning(s"Attempted to release $size bytes of storage " +
  95. s"memory when we only have ${_memoryUsed} bytes")
  96. _memoryUsed = 0
  97. } else {
  98. // 否则,已使用内存_memoryUsed减去size大小
  99. _memoryUsed -= size
  100. }
  101. }
  102. // 释放所有的内存,同样需要lock对象上的synchronized关键字,解决并发问题,将目前已使用内存_memoryUsed设置为0
  103. def releaseAllMemory(): Unit = lock.synchronized {
  104. _memoryUsed = 0
  105. }
  106. /**
  107. * Try to shrink the size of this storage memory pool by `spaceToFree` bytes. Return the number
  108. * of bytes removed from the pool's capacity.
  109. */
  110. def shrinkPoolToFreeSpace(spaceToFree: Long): Long = lock.synchronized {
  111. // First, shrink the pool by reclaiming free memory:
  112. val spaceFreedByReleasingUnusedMemory = math.min(spaceToFree, memoryFree)
  113. decrementPoolSize(spaceFreedByReleasingUnusedMemory)
  114. val remainingSpaceToFree = spaceToFree - spaceFreedByReleasingUnusedMemory
  115. if (remainingSpaceToFree > 0) {
  116. // If reclaiming free memory did not adequately shrink the pool, begin evicting blocks:
  117. val evictedBlocks = new ArrayBuffer[(BlockId, BlockStatus)]
  118. memoryStore.evictBlocksToFreeSpace(None, remainingSpaceToFree, evictedBlocks)
  119. val spaceFreedByEviction = evictedBlocks.map(_._2.memSize).sum
  120. // When a block is released, BlockManager.dropFromMemory() calls releaseMemory(), so we do
  121. // not need to decrement _memoryUsed here. However, we do need to decrement the pool size.
  122. decrementPoolSize(spaceFreedByEviction)
  123. spaceFreedByReleasingUnusedMemory + spaceFreedByEviction
  124. } else {
  125. spaceFreedByReleasingUnusedMemory
  126. }
  127. }
  128. }

我们重点看下acquireMemory()的两个方法,第一个是带有blockId、numBytes、evictedBlocks三个参数的,它的逻辑很简单,使用lock的synchronized,解决并发的问题,然后计算需要释放的内存大小numBytesToFree,需要申请的大小减去内存池目前可用内存大小,也就是看内存池中可用内存大小是否能满足申请分配的内存大小,然后调用多一个numBytesToFree参数的同名方法。

带有四个参数的acquireMemory()也很简单,首先需要做一些内存大小的校验,确保内存的申请分配时合理的。校验的内容包含以下三个部分:

1、申请分配的内存numBytesToAcquire必须大于等于0;

2、需要释放的内存numBytesToFree必须大于等于0;

3、已使用内存memoryUsed必须小于等于内存池大小poolSize;

然后,如果需要释放部分内存,即numBytesToFree大于0,则调用MemoryStore的evictBlocksToFreeSpace()方法释放numBytesToFree大小内存,关于MemoryStore的内容我们在后续的存储管理模块再详细介绍,这里先有个概念即可。

最后,判断是否有足够的内存,即申请分配的内存必须小于等于可用内存,如果有足够的内存,已使用内存_memoryUsed增加numBytesToAcquire,并返回ture,否则返回false。

接下来,我们再看下shrinkPoolToFreeSpace()方法,它的主要作用就是试图对storage内存池收缩 spaceToFree字节大小,返回实际收缩的大小值。处理逻辑如下:

1、取试图收缩大小spaceToFree和可用内存memoryFree的较小者,即如果试图收缩的spaceToFree大于可用内存大小,那么最大也就是收缩可用内存大小memoryFree;

2、内存池做相应的减少,减少的大小为上面的spaceFreedByReleasingUnusedMemory;

3、计算预设定收缩大小中未完成的部分remainingSpaceToFree,即spaceToFree - spaceFreedByReleasingUnusedMemory;

4、如果未完成部分大于0:

4.1、利用MemoryStore调用evictBlocksToFreeSpace,放弃部分块来增加内存可用空间;

4.2、取得放弃块后可用内存增加的大小spaceFreedByEviction;

4.3、内存池做相应的减少spaceFreedByEviction;

4.4、返回收缩的实际大小,即spaceFreedByReleasingUnusedMemory + spaceFreedByEviction;

5、返回spaceFreedByReleasingUnusedMemory。

相对应的,我们现在来看下ExecutionMemoryPool的实现,代码如下:

  1. /**
  2. * Implements policies and bookkeeping for sharing a adjustable-sized pool of memory between tasks.
  3. *
  4. * Tries to ensure that each task gets a reasonable share of memory, instead of some task ramping up
  5. * to a large amount first and then causing others to spill to disk repeatedly.
  6. *
  7. * If there are N tasks, it ensures that each task can acquire at least 1 / 2N of the memory
  8. * before it has to spill, and at most 1 / N. Because N varies dynamically, we keep track of the
  9. * set of active tasks and redo the calculations of 1 / 2N and 1 / N in waiting tasks whenever this
  10. * set changes. This is all done by synchronizing access to mutable state and using wait() and
  11. * notifyAll() to signal changes to callers. Prior to Spark 1.6, this arbitration of memory across
  12. * tasks was performed by the ShuffleMemoryManager.
  13. *
  14. * @param lock a [[MemoryManager]] instance to synchronize on
  15. * @param poolName a human-readable name for this pool, for use in log messages
  16. */
  17. private[memory] class ExecutionMemoryPool(
  18. lock: Object,
  19. poolName: String
  20. ) extends MemoryPool(lock) with Logging {
  21. /**
  22. * Map from taskAttemptId -> memory consumption in bytes
  23. * taskAttemptId到内存耗费的映射
  24. */
  25. @GuardedBy("lock")
  26. private val memoryForTask = new mutable.HashMap[Long, Long]()
  27. // 获取已使用内存,需要在对象lock上使用synchronized关键字,解决并发的问题
  28. override def memoryUsed: Long = lock.synchronized {
  29. memoryForTask.values.sum
  30. }
  31. /**
  32. * Returns the memory consumption, in bytes, for the given task.
  33. * 返回给定Task的内存耗费
  34. */
  35. def getMemoryUsageForTask(taskAttemptId: Long): Long = lock.synchronized {
  36. memoryForTask.getOrElse(taskAttemptId, 0L)
  37. }
  38. /**
  39. * Try to acquire up to `numBytes` of memory for the given task and return the number of bytes
  40. * obtained, or 0 if none can be allocated.
  41. *
  42. * This call may block until there is enough free memory in some situations, to make sure each
  43. * task has a chance to ramp up to at least 1 / 2N of the total memory pool (where N is the # of
  44. * active tasks) before it is forced to spill. This can happen if the number of tasks increase
  45. * but an older task had a lot of memory already.
  46. *
  47. * @param numBytes number of bytes to acquire
  48. * @param taskAttemptId the task attempt acquiring memory
  49. * @param maybeGrowPool a callback that potentially grows the size of this pool. It takes in
  50. *                      one parameter (Long) that represents the desired amount of memory by
  51. *                      which this pool should be expanded.
  52. * @param computeMaxPoolSize a callback that returns the maximum allowable size of this pool
  53. *                           at this given moment. This is not a field because the max pool
  54. *                           size is variable in certain cases. For instance, in unified
  55. *                           memory management, the execution pool can be expanded by evicting
  56. *                           cached blocks, thereby shrinking the storage pool.
  57. *
  58. * @return the number of bytes granted to the task.
  59. */
  60. private[memory] def acquireMemory(
  61. numBytes: Long,
  62. taskAttemptId: Long,
  63. maybeGrowPool: Long => Unit = (additionalSpaceNeeded: Long) => Unit,
  64. computeMaxPoolSize: () => Long = () => poolSize): Long = lock.synchronized {
  65. // 申请内存numBytes的大小必须大于0
  66. assert(numBytes > 0, s"invalid number of bytes requested: $numBytes")
  67. // TODO: clean up this clunky method signature
  68. // Add this task to the taskMemory map just so we can keep an accurate count of the number
  69. // of active tasks, to let other tasks ramp down their memory in calls to `acquireMemory`
  70. // 如果memoryForTask中不包含该Task,加入该Task,初始化为0,并唤醒其它等待的对象
  71. if (!memoryForTask.contains(taskAttemptId)) {
  72. memoryForTask(taskAttemptId) = 0L
  73. // This will later cause waiting tasks to wake up and check numTasks again
  74. lock.notifyAll()
  75. }
  76. // Keep looping until we're either sure that we don't want to grant this request (because this
  77. // task would have more than 1 / numActiveTasks of the memory) or we have enough free
  78. // memory to give it (we always let each task get at least 1 / (2 * numActiveTasks)).
  79. // TODO: simplify this to limit each task to its own slot
  80. while (true) {
  81. // 获取当前活跃Task的数目
  82. val numActiveTasks = memoryForTask.keys.size
  83. // 获取该Task对应的当前已耗费内存
  84. val curMem = memoryForTask(taskAttemptId)
  85. // In every iteration of this loop, we should first try to reclaim any borrowed execution
  86. // space from storage. This is necessary because of the potential race condition where new
  87. // storage blocks may steal the free execution memory that this task was waiting for.
  88. // 传进来的UnifiedMemoryManager的maybeGrowExecutionPool()方法
  89. // 通过收回缓存的块扩充the execution pool,从而减少the storage pool
  90. maybeGrowPool(numBytes - memoryFree)
  91. // Maximum size the pool would have after potentially growing the pool.
  92. // This is used to compute the upper bound of how much memory each task can occupy. This
  93. // must take into account potential free memory as well as the amount this pool currently
  94. // occupies. Otherwise, we may run into SPARK-12155 where, in unified memory management,
  95. // we did not take into account space that could have been freed by evicting cached blocks.
  96. // 计算内存池的最大大小maxPoolSize
  97. val maxPoolSize = computeMaxPoolSize()
  98. // 平均每个Task分配的最大内存大小maxMemoryPerTask
  99. val maxMemoryPerTask = maxPoolSize / numActiveTasks
  100. // 平均每个Task分配的最小内存大小minMemoryPerTask,为maxMemoryPerTask的一半
  101. val minMemoryPerTask = poolSize / (2 * numActiveTasks)
  102. // How much we can grant this task; keep its share within 0 <= X <= 1 / numActiveTasks
  103. // 我们可以赋予该Task的最大大小,取numBytes和(maxMemoryPerTask - curMem与0较大者)中的较小者
  104. // 如果当前已耗费内存大于maxMemoryPerTask,则为0,不再分配啦,否则取还可以分配的内存和申请分配的内存中的较小者
  105. val maxToGrant = math.min(numBytes, math.max(0, maxMemoryPerTask - curMem))
  106. // Only give it as much memory as is free, which might be none if it reached 1 / numTasks
  107. // 实际可以分配的最大大小,取maxToGrant和memoryFree中的较小者
  108. val toGrant = math.min(maxToGrant, memoryFree)
  109. // We want to let each task get at least 1 / (2 * numActiveTasks) before blocking;
  110. // if we can't give it this much now, wait for other tasks to free up memory
  111. // (this happens if older tasks allocated lots of memory before N grew)
  112. if (toGrant < numBytes && curMem + toGrant < minMemoryPerTask) {
  113. // 如果实际分配的内存大小toGrant小于申请分配的内存大小numBytes,且当前已耗费内存加上马上就要分配的内存,小于Task需要的最小内存
  114. // 记录日志信息
  115. logInfo(s"TID $taskAttemptId waiting for at least 1/2N of $poolName pool to be free")
  116. // lock等待,即MemoryManager等待
  117. lock.wait()
  118. } else {
  119. // 对应Task的已耗费内存增加toGrant
  120. memoryForTask(taskAttemptId) += toGrant
  121. // 返回申请的内存大小toGrant
  122. return toGrant
  123. }
  124. }
  125. 0L  // Never reached
  126. }
  127. /**
  128. * Release `numBytes` of memory acquired by the given task.
  129. * 释放给定Task申请的numBytes大小的内存
  130. */
  131. def releaseMemory(numBytes: Long, taskAttemptId: Long): Unit = lock.synchronized {
  132. // 根据Task获取当前已耗费内存
  133. val curMem = memoryForTask.getOrElse(taskAttemptId, 0L)
  134. var memoryToFree = if (curMem < numBytes) {// 如果当前已耗费内存小于需要释放的内存
  135. // 记录警告日志信息
  136. logWarning(
  137. s"Internal error: release called on $numBytes bytes but task only has $curMem bytes " +
  138. s"of memory from the $poolName pool")
  139. // 返回curMem
  140. curMem
  141. } else {
  142. // 否则直接返回numBytes
  143. numBytes
  144. }
  145. if (memoryForTask.contains(taskAttemptId)) {
  146. // memoryForTask中对应Task的已耗费内存减少memoryToFree
  147. memoryForTask(taskAttemptId) -= memoryToFree
  148. // 已耗费内存小于等于0的话,直接删除
  149. if (memoryForTask(taskAttemptId) <= 0) {
  150. memoryForTask.remove(taskAttemptId)
  151. }
  152. }
  153. // 唤醒所有等待的对象,比如acquireMemory()方法
  154. lock.notifyAll() // Notify waiters in acquireMemory() that memory has been freed
  155. }
  156. /**
  157. * Release all memory for the given task and mark it as inactive (e.g. when a task ends).
  158. * @return the number of bytes freed.
  159. * 释放给定Task的所有内存,并且标记其为不活跃
  160. */
  161. def releaseAllMemoryForTask(taskAttemptId: Long): Long = lock.synchronized {
  162. // 获取指定Task的内存使用情况
  163. val numBytesToFree = getMemoryUsageForTask(taskAttemptId)
  164. // 释放指定Task的numBytesToFree大小的内存
  165. releaseMemory(numBytesToFree, taskAttemptId)
  166. // 返回释放的大小numBytesToFree
  167. numBytesToFree
  168. }
  169. }

其中,有一个非常重要的数据结构memoryForTask,保存的是taskAttemptId到内存耗费的映射。

我们还是重点看下acquireMemory()方法,主要逻辑如下:

1、校验,确保申请内存numBytes的大小必须大于0;

2、如果memoryForTask中不包含该Task,加入该Task,初始化为0,并唤醒其它等待的对象;

3、在一个循环体中:

3.1、获取当前活跃Task的数目numActiveTasks;

3.2、获取该Task对应的当前已耗费内存curMem;

3.3、maybeGrowPool为传进来的UnifiedMemoryManager的maybeGrowExecutionPool()方法,其通过收回缓存的块扩充the execution pool,从而减少the storage pool;

3.4、计算内存池的最大大小maxPoolSize;

3.5、平均每个Task分配的最大内存大小maxMemoryPerTask;

3.6、平均每个Task分配的最小内存大小minMemoryPerTask,为maxMemoryPerTask的一半;

3.7、计算我们可以赋予该Task的最大大小maxToGrant,取numBytes和(maxMemoryPerTask - curMem与0较大者)中的较小者,也就是,如果当前已耗费内存大于maxMemoryPerTask,则为0,不再分配啦,否则取还可以分配的内存和申请分配的内存中的较小者;

3.8、计算实际可以分配的最大大小toGrant,取maxToGrant和memoryFree中的较小者;

3.9、如果实际分配的内存大小toGrant小于申请分配的内存大小numBytes,且当前已耗费内存加上马上就要分配的内存,小于Task需要的最小内存,记录日志信息,lock等待,即MemoryManager等待;否则memoryForTask中对应Task的已耗费内存增加toGrant,返回申请的内存大小toGrant,跳出循环。

好了,到此为止,静态内存管理模型StaticMemoryManager和统一内存管理模型UnifiedMemoryManager的原理、初始化,还有storage区域和execution区域内存申请的时机、具体策略及方法我们都已分析完了。因水平有限,如有叙述不清、错误的地方,或者好的建议和更深的理解,还望诸位读者不吝赐教!其中涉及的storage、shuffle等内容或者相关类,等后续的存储模块、shuffle模块再做详细分析吧!

只看不评,不是好汉!哈哈!

博客原地址:http://blog.csdn.net/lipeng_bigdata/article/details/50752297

最新文章

  1. Signlar
  2. 关于Java的软引用及弱引用
  3. Unix sed实用教程开篇
  4. 7个鲜为人知却超实用的PHP函数
  5. Emgu CV 高斯建模
  6. SSDT – Error SQL70001 This statement is not recognized in this context-摘自网络
  7. mysql 查询表
  8. sql定期移植数据的存储过程
  9. openstack创建实例测试步骤
  10. Problem H
  11. C++中模板template &lt;typename T&gt;
  12. 自动化运维工具——puppet详解(一)
  13. Python之几种常用模块
  14. 2016年年终CSDN博客总结
  15. 如何设置织梦cms自定义表单字段为必填项
  16. Mac 装Sequel pro 连接 Mysql 8.0 失败、登录不了、loading问题
  17. odoo 开发基础 -- 视图之xpath语法
  18. Redis未授权漏洞利用方式
  19. vue-cli 添加到生产环境问题总结
  20. GDI+中发生一般性错误的解决办法(转)

热门文章

  1. js汉字转拼音首字母
  2. 有道词典中的OCR功能:第三方库的变化
  3. window postgresql 10.4安装
  4. LeetCode OJ-- LRU Cache ***@
  5. BZOJ1054(搜索)
  6. Unity工程资源破解
  7. 洛谷——P2383 狗哥玩木棒
  8. codevs——2841 愤怒的LJF(背包)
  9. IE6~IE7 bugs
  10. Codeforces Round #298 (Div. 2) A、B、C题