新用户注册入口 老用户登录入口

[转载]JVM G1源码分析(一)——卡表和位图

文章作者:转载 更新时间:2023-12-16 20:37:50 阅读数量:245
文章标签:G1垃圾收集器RSet内存分区引用关系标记垃圾回收效率地址映射
本文摘要:卡表(CardTable)是垃圾收集器中用于快速识别堆内存分区间引用关系的核心数据结构,尤其在CMS和G1收集器中扮演关键角色。为提升垃圾回收效率,卡表借助位图思想记录对象引用信息:当A分区的对象objA引用B分区的objB时,会在A分区对应的卡表项中标记引用。CardTable类提供了一系列方法实现卡表初始化、查询更新以及地址到卡表条目的映射。在G1中,卡表与RSet结合使用,进一步优化了跨分区引用跟踪。通过卡表,垃圾收集器能够高效并发地遍历活跃对象,减少STW时间,提高系统性能。
转载文章

本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_16500963/article/details/132133125。

该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。

作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。

如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。

卡表(CardTable)在CMS中是最常见的概念之一,G1中不仅保留了这个概念,还引入了RSet。卡表到底是一个什么东西?GC最早引入卡表的目的是为了对内存的引用关系做标记,从而根据引用关系快速遍历活跃对象。举个简单的例子,有两个分区,假设分区大小都为1MB,分别为A和B。如果A中有一个对象objA,B中有一个对象objB,且objA.field=objB,那么这两个分区就有引用关系了,但是如果我们想找到分区A,要如何引用分区B?做法有两种:·遍历整个分区A,一个字一个字的移动(为什么以字为单位?原因是JVM中对象会对齐,所以不需要按字节移动),然后查看内存里面的值到底是不是指向B,这种方法效率太低,可以优化为一个对象一个对象地移动(这里涉及JVM如何识别对象,以及如何区分指针和立即数),但效率还是太低。

·借助额外的数据结构描述这种引用关系,例如使用类似位图(bitmap)的方法,记录A和B的内存块之间的引用关系,用一个位来描述一个字,假设在32位机器上(一个字为32位),需要32KB(32KB×32=1M)的空间来描述一个分区。那么我们就可以在这个对象ObjA所在分区A里面添加一个额外的指针,这个指针指向另外一个分区B的位图,如果我们可以把对象ObjA和指针关系进行映射,那么当访问ObjA的时候,顺便访问这个额外的指针,从这个指针指向的位图就能找到被ObjA引用的分区B对应的内存块。通常我们只需要判定位图里面对应的位是否有1,有的话则认为发生了引用。

class CardTable: public CHeapObj<mtGC> {friend class VMStructs;
public:typedef uint8_t CardValue;// All code generators assume that the size of a card table entry is one byte.// They need to be updated to reflect any change to this.// This code can typically be found by searching for the byte_map_base() method.STATIC_ASSERT(sizeof(CardValue) == 1);protected:// The declaration order of these const fields is important; see the// constructor before changing.const MemRegion _whole_heap;       // the region covered by the card tableconst size_t    _page_size;        // page size used when mapping _byte_mapsize_t          _byte_map_size;    // in bytesCardValue*      _byte_map;         // the card marking arrayCardValue*      _byte_map_base;// Some barrier sets create tables whose elements correspond to parts of// the heap; the CardTableBarrierSet is an example.  Such barrier sets will// normally reserve space for such tables, and commit parts of the table// "covering" parts of the heap that are committed. At most one covered// region per generation is needed.static constexpr int max_covered_regions = 2;// The covered regions should be in address order.MemRegion _covered[max_covered_regions];// The last card is a guard card; never committed.MemRegion _guard_region;inline size_t compute_byte_map_size(size_t num_bytes);enum CardValues {clean_card                  = (CardValue)-1,dirty_card                  =  0,CT_MR_BS_last_reserved      =  1};// a word's worth (row) of clean card valuesstatic const intptr_t clean_card_row = (intptr_t)(-1);// CardTable entry sizestatic uint _card_shift;static uint _card_size;static uint _card_size_in_words;size_t last_valid_index() const {return cards_required(_whole_heap.word_size()) - 1;}private:void initialize_covered_region(void* region0_start, void* region1_start);MemRegion committed_for(const MemRegion mr) const;
public:CardTable(MemRegion whole_heap);virtual ~CardTable() = default;void initialize(void* region0_start, void* region1_start);// *** Barrier set functions.// Initialization utilities; covered_words is the size of the covered region// in, um, words.inline size_t cards_required(size_t covered_words) const {assert(is_aligned(covered_words, _card_size_in_words), "precondition");return covered_words / _card_size_in_words;}// Dirty the bytes corresponding to "mr" (not all of which must be// covered.)void dirty_MemRegion(MemRegion mr);// Clear (to clean_card) the bytes entirely contained within "mr" (not// all of which must be covered.)void clear_MemRegion(MemRegion mr);// Return true if "p" is at the start of a card.bool is_card_aligned(HeapWord* p) {CardValue* pcard = byte_for(p);return (addr_for(pcard) == p);}// Mapping from address to card marking array entryCardValue* byte_for(const void* p) const {assert(_whole_heap.contains(p),"Attempt to access p = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end()));CardValue* result = &_byte_map_base[uintptr_t(p) >> _card_shift];assert(result >= _byte_map && result < _byte_map + _byte_map_size,"out of bounds accessor for card marking array");return result;}// The card table byte one after the card marking array// entry for argument address. Typically used for higher bounds// for loops iterating through the card table.CardValue* byte_after(const void* p) const {return byte_for(p) + 1;}void invalidate(MemRegion mr);// Provide read-only access to the card table array.const CardValue* byte_for_const(const void* p) const {return byte_for(p);}const CardValue* byte_after_const(const void* p) const {return byte_after(p);}// Mapping from card marking array entry to address of first wordHeapWord* addr_for(const CardValue* p) const {assert(p >= _byte_map && p < _byte_map + _byte_map_size,"out of bounds access to card marking array. p: " PTR_FORMAT" _byte_map: " PTR_FORMAT " _byte_map + _byte_map_size: " PTR_FORMAT,p2i(p), p2i(_byte_map), p2i(_byte_map + _byte_map_size));// As _byte_map_base may be "negative" (the card table has been allocated before// the heap in memory), do not use pointer_delta() to avoid the assertion failure.size_t delta = p - _byte_map_base;HeapWord* result = (HeapWord*) (delta << _card_shift);assert(_whole_heap.contains(result),"Returning result = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(result), p2i(_whole_heap.start()), p2i(_whole_heap.end()));return result;}// Mapping from address to card marking array index.size_t index_for(void* p) {assert(_whole_heap.contains(p),"Attempt to access p = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end()));return byte_for(p) - _byte_map;}CardValue* byte_for_index(const size_t card_index) const {return _byte_map + card_index;}// Resize one of the regions covered by the remembered set.void resize_covered_region(MemRegion new_region);// *** Card-table-RemSet-specific things.static uintx ct_max_alignment_constraint();static uint card_shift() {return _card_shift;}static uint card_size() {return _card_size;}static uint card_size_in_words() {return _card_size_in_words;}static constexpr CardValue clean_card_val()          { return clean_card; }static constexpr CardValue dirty_card_val()          { return dirty_card; }static intptr_t clean_card_row_val()   { return clean_card_row; }// Initialize card sizestatic void initialize_card_size();// Card marking array base (adjusted for heap low boundary)// This would be the 0th element of _byte_map, if the heap started at 0x0.// But since the heap starts at some higher address, this points to somewhere// before the beginning of the actual _byte_map.CardValue* byte_map_base() const { return _byte_map_base; }virtual bool is_in_young(const void* p) const = 0;
};

class G1CardTable : public CardTable {friend class VMStructs;friend class G1CardTableChangedListener;G1CardTableChangedListener _listener;public:enum G1CardValues {g1_young_gen = CT_MR_BS_last_reserved << 1,// During evacuation we use the card table to consolidate the cards we need to// scan for roots onto the card table from the various sources. Further it is// used to record already completely scanned cards to avoid re-scanning them// when incrementally evacuating the old gen regions of a collection set.// This means that already scanned cards should be preserved.//// The merge at the start of each evacuation round simply sets cards to dirty// that are clean; scanned cards are set to 0x1.//// This means that the LSB determines what to do with the card during evacuation// given the following possible values://// 11111111 - clean, do not scan// 00000001 - already scanned, do not scan// 00000000 - dirty, needs to be scanned.//g1_card_already_scanned = 0x1};static const size_t WordAllClean = SIZE_MAX;static const size_t WordAllDirty = 0;STATIC_ASSERT(BitsPerByte == 8);static const size_t WordAlreadyScanned = (SIZE_MAX / 255) * g1_card_already_scanned;G1CardTable(MemRegion whole_heap): CardTable(whole_heap), _listener() {_listener.set_card_table(this);}static CardValue g1_young_card_val() { return g1_young_gen; }static CardValue g1_scanned_card_val() { return g1_card_already_scanned; }void verify_g1_young_region(MemRegion mr) PRODUCT_RETURN;void g1_mark_as_young(const MemRegion& mr);size_t index_for_cardvalue(CardValue const* p) const {return pointer_delta(p, _byte_map, sizeof(CardValue));}// Mark the given card as Dirty if it is Clean. Returns whether the card was// Clean before this operation. This result may be inaccurate as it does not// perform the dirtying atomically.inline bool mark_clean_as_dirty(CardValue* card);// Change Clean cards in a (large) area on the card table as Dirty, preserving// already scanned cards. Assumes that most cards in that area are Clean.inline void mark_range_dirty(size_t start_card_index, size_t num_cards);// Change the given range of dirty cards to "which". All of these cards must be Dirty.inline void change_dirty_cards_to(CardValue* start_card, CardValue* end_card, CardValue which);inline uint region_idx_for(CardValue* p);static size_t compute_size(size_t mem_region_size_in_words) {size_t number_of_slots = (mem_region_size_in_words / _card_size_in_words);return ReservedSpace::allocation_align_size_up(number_of_slots);}// Returns how many bytes of the heap a single byte of the Card Table corresponds to.static size_t heap_map_factor() { return _card_size; }void initialize(G1RegionToSpaceMapper* mapper);bool is_in_young(const void* p) const override;
};

以位为粒度的位图能准确描述每一个字的引用关系,但是一个位通常包含的信息太少,只能描述2个状态:引用还是未引用。实际应用中JVM在垃圾回收的时候需要更多的状态,如果增加至一个字节来描述状态,则位图需要256KB的空间,这个数字太大,开销占了25%。所以一个可能的做法位图不再描述一个字,而是一个区域,JVM选择512字节为单位,即用一个字节描述512字节的引用关系。选择一个区域除了空间利用率的问题之外,实际上还有现实的意义。我们知道Java对象实际上不是一个字能描述的(有一个参数可以控制对象最小对齐的大小,默认是8字节,实际上Java在JVM中还有一些附加信息,所以对齐后最小的Java对象是16字节),很多Java对象可能是几十个字节或者几百个字节,所以用一个字节描述一个区域是有意义的。但是我没有找到512的来源,为什么512效果最好?没有相应的数据来支持这个数字,而且这个值不可以配置,不能修改,但是有理由相信512字节的区域是为了节约内存额外开销。按照这个值,1MB的内存只需要2KB的额外空间就能描述引用关系。这又带来另一个问题,就是512字节里面的内存可能被引用多次,所以这是一个粗略的关系描述,那么在使用的时候需要遍历这512字节。

再举一个例子,假设有两个对象B、C都在这512字节的区域内。为了方便处理,记录对象引用关系的时候,都使用对象的起始位置,然后用这个地址和512对齐,因此B和C对象的卡表指针都指向这一个卡表的位置。那么对于引用处理也有可有两种处理方法:·处理的时候会以堆分区为处理单位,遍历整个堆分区,在遍历的时候,每次都会以对象大小为步长,结合卡表,如果该卡表中对应的位置被设置,则说明对象和其他分区的对象发生了引用。具体内容在后文中介绍Refine的时候还会详细介绍。·处理的时候借助于额外的数据结构,找到真正对象的位置,而不需要从头开始遍历。在后文的并发标记处理时就使用了这种方法,用于找到第一个对象的起始位置。在G1除了512字节粒度的卡表之外,还有bitMap,例如使用bitMap可以描述一个分区对另外一个分区的引用情况。在JVM中bitMap使用非常多,例如还可以描述内存的分配情况。

在G1除了512字节粒度的卡表之外,还有bitMap,例如使用bitMap可以描述一个分区对另外一个分区的引用情况。在JVM中bitMap使用非常多,例如还可以描述内存的分配情况。G1在混合收集算法中用到了并发标记。在并发标记的时候使用了bitMap来描述对象的分配情况。例如1MB的分区可以用16KB(16KB×ObjectAlignmentInBytes×8=1MB)来描述,即16KB额外的空间。其中ObjectAlignmentInBytes是8字节,指的是对象对齐,第二个8是指一个字节有8位。即每一个位可以描述64位。例如一个对象长度对齐之后为24字节,理论上它占用3个位来描述这个24字节已被使用了,实际上并不需要,在标记的时候只需要标记这3个位中的第一个位,再结合堆分区对象的大小信息就能准确找出。其最主要的目的是为了效率,标记一个位和标记3个位相比能节约不少时间,如果对象很大,则更划算。这些都是源码的实现细节,大家在阅读源码时需要细细斟酌。

本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_16500963/article/details/132133125。

该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。

作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。

如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。

相关阅读
文章标题:[转载][洛谷P1082]同余方程

更新时间:2023-02-18
[转载][洛谷P1082]同余方程
文章标题:[转载]webpack优化之HappyPack实战

更新时间:2023-08-07
[转载]webpack优化之HappyPack实战
文章标题:[转载]oracle 同时更新多表,在Oracle数据库中同时更新两张表的简单方法

更新时间:2023-09-10
[转载]oracle 同时更新多表,在Oracle数据库中同时更新两张表的简单方法
文章标题:[转载][Unity] 包括场景互动与射击要素的俯视角闯关游戏Demo

更新时间:2024-03-11
[转载][Unity] 包括场景互动与射击要素的俯视角闯关游戏Demo
文章标题:[转载]程序员也分三六九等?等级差异,一个看不起一个!

更新时间:2024-05-10
[转载]程序员也分三六九等?等级差异,一个看不起一个!
文章标题:[转载]海贼王 动漫 全集目录 分章节 精彩打斗剧集

更新时间:2024-01-12
[转载]海贼王 动漫 全集目录 分章节 精彩打斗剧集
名词解释
作为当前文章的名词解释,仅对当前文章有效。
CardTableCardTable是Java垃圾收集器中用于追踪堆内存分区之间对象引用关系的数据结构。在JVM的内存管理中,它以卡片(card)为单位划分堆内存空间,并通过一个字节(或多个字节表示的状态位)来记录每个卡片区域内的对象是否有跨分区引用。当某卡片区域内的对象引用了其他分区的对象时,会在该卡片对应的卡表项中标记,便于垃圾回收器快速识别哪些分区可能存在活跃对象,从而提高垃圾回收效率。
CMS (Concurrent Mark Sweep) 垃圾收集器CMS是HotSpot虚拟机提供的一种并发标记清除垃圾收集器,主要用于服务端应用。其主要特点是大部分工作可以在应用线程并发执行,减少了系统暂停时间(Stop-The-World)。在CMS收集周期中,通过使用卡表(CardTable)等数据结构来跟踪对象引用变化,并采用多阶段算法实现对堆内存的并发标记、初始标记、重新标记和并发清除操作,旨在实现实时性要求较高的场景下高效稳定的垃圾回收。
G1 (Garbage First) 垃圾收集器G1是Oracle JDK 9及以后版本中的默认垃圾收集器,适用于大内存应用环境。G1将整个堆划分为多个大小相等的region,并引入Remembered Set(RSet)与CardTable结合,更精细化地追踪跨区域引用。G1设计目标是在保持低延迟的同时处理大规模堆内存,其垃圾回收过程包括并发标记、初始标记、最终标记、混合回收等阶段,并能预测停顿时间和自动进行堆压缩,提高了GC性能和资源利用率。
Remembered Set (RSet)RSet是G1垃圾收集器中一种额外的数据结构,用于记录某个内存分区(Region)内部指向其他分区对象的引用信息。相较于传统的卡表仅记录是否存在跨分区引用,RSet更加详细地记录了具体指向哪些分区的引用,使得垃圾回收器在并发标记过程中能够快速准确地找到跨分区引用,进而显著提升回收效率和减少STW(Stop-The-World)停顿时间。
延伸阅读
作为当前文章的延伸阅读,仅对当前文章有效。
在深入理解卡表(CardTable)在Java垃圾收集器中的作用之后,进一步的延伸阅读可以从以下几个方向进行:
1. 最新GC算法进展:随着JDK版本的不断更新,Oracle和OpenJDK社区对垃圾收集器进行了持续优化。例如,最新的ZGC和Shenandoah GC采用了更为先进的内存管理技术,如颜色指针、读屏障等,以实现更低延迟的并发标记清理过程。关注这些前沿GC算法的研究与发展,可以更全面地了解现代JVM如何高效处理大规模堆内存引用关系。
2. G1垃圾收集器与RSet深入解读:G1作为当前HotSpot JVM推荐的默认垃圾收集器,其内部机制中除了卡表外,Remembered Set(RSet)也是关键组件。详细了解RSet如何辅助卡表追踪跨区域引用,以及分区并发压缩等特性,将有助于读者掌握G1高效回收内存的具体实现原理。
3. 实际生产环境案例分析:通过阅读一些大型互联网企业或开源社区分享的实战经验文章,了解他们在使用CMS、G1等垃圾收集器时如何针对特定业务场景调整卡表相关参数,解决实际遇到的性能瓶颈问题。比如,如何根据应用特点选择合适的卡表大小、调整扫描频率以平衡GC开销与应用响应时间。
4. 学术研究论文:查阅近年来关于垃圾收集器优化的学术论文,比如《A Study of the G1 Garbage Collector》、《The Z Garbage Collector》等,可深入了解卡表设计背后的理论依据,以及研究人员为提升GC效率所做的各种尝试和改进。
5. 官方文档及源码阅读:直接研读Oracle官方发布的Java SE HotSpot VM Garbage Collection Tuning Guide,以及JDK源码中的CardTableBarrierSet等相关类实现,可以更直观地把握卡表的具体工作流程和技术细节。同时,关注JDK开发团队的博客、邮件列表讨论等,获取第一手的更新信息和未来发展方向。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
tar --list -f archive.tar.gz - 列出归档文件中的内容。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
HessianRPC在高负载下服务降级与熔断器模式保障用户体验 05-01 jQuery和TweenMax简单实用的水平手风琴特效 01-20 jquery选择国家下拉列表框插件 01-21 Sqoop在Hadoop集群中的数据传输机制及数据库迁移、收集与备份恢复应用实践 12-23 简约渔具批发牧渔企业类网站前端模板下载 11-09 基于bootstrap功能齐全的jQuery进度条插件 10-20 简约大气男性护肤产品HTML5网站模板 09-22 宽屏大气机械设备制造公司网站模板 08-13 演讲会门票销售网站模板下载 07-30 本次刷新还10个文章未展示,点击 更多查看。
经典响应式投资理财企业前端模板 06-26 基于Redis的键值对存储实现用户阅读状态跟踪与管理 06-24 Netty框架中CannotFindServerSelection异常:服务器地址配置错误与通道类型匹配详解 06-18 简洁设计公司响应式网站模板下载 05-06 绿色苗木草坪种植绿化类企业前端CMS模板下载 04-30 怎么在cmd开启mysql服务 04-15 保洁公司家庭保洁服务网站模板 03-26 SpringCloud微服务中分布式锁的死锁问题与状态一致性维护:避免循环依赖、公平锁及超时重试机制在Redisson中的实践运用 03-19 HBase性能测试与RegionServer配置、架构及数据模型调优实践:关注响应时间、并发处理能力与BlockCache优化 03-14 jquery控制radio触发事件 02-15 简约HTML5软件营销业务公司网站模板 02-09
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"