Advanced .NET Debugging: Managed Heap and Garbage Collection(转载,托管堆查内存碎片问题解决思路)
原文地址:http://www.informit.com/articles/article.aspx?p=1409801&seqNum=4
Debugging Managed Heap Fragmentation
Earlier in the chapter, we described a phenomenon known as heap fragmentation, in which free and busy blocks are arranged and interleaved on the managed heap in such a way that they can cause problems in applications that surface as OutOfMemory exceptions; in reality, enough memory is free, just not in a contiguous fashion. The CLR heap manager utilizes a technique known as compacting and coalescing to reduce the risk of heap fragmentation. In this section, we will take a look at an example that can cause heap fragmentation to occur and how we can use the debuggers to identify that a heap fragmentation is in fact occurring and the reasons behind it. The example is shown in Listing 5-8.
Listing 5-8. Heap fragmentation example
using System;
using System.Text;
using System.Runtime.InteropServices; namespace Advanced.NET.Debugging.Chapter5
{
class Fragment
{
static void Main(string[] args)
{
Fragment f = new Fragment();
f.Run(args);
} public void Run(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("05Fragment.exe <alloc. size> <max mem in MB>");
return;
} int size = Int32.Parse(args[0]);
int maxmem = Int32.Parse(args[1]);
byte[][] nonPinned = null;
byte[][] pinned = null;
GCHandle[] pinnedHandles = null; int numAllocs=maxmem*1000000/size; pinnedHandles = new GCHandle[numAllocs]; pinned = new byte[numAllocs / 2][];
nonPinned = new byte[numAllocs / 2][]; for (int i = 0; i < numAllocs / 2; i++)
{
nonPinned[i] = new byte[size];
pinned[i] = new byte[size];
pinnedHandles[i] =
GCHandle.Alloc(pinned[i], GCHandleType.Pinned);
}
Console.WriteLine("Press any key to GC & promo to gen1");
Console.ReadKey(); GC.Collect(); Console.WriteLine("Press any key to GC & promo to gen2");
Console.ReadKey(); GC.Collect(); Console.WriteLine("Press any key to GC(free non pinned");
Console.ReadKey(); for (int i = 0; i < numAllocs / 2; i++)
{
nonPinned[i] = null;
} GC.Collect(); Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
The source code and binary for Listing 5-8 can be found in the following folders:
- Source code: C:\ADND\Chapter5\Fragment
- Binary: C:\ADNDBin\05Fragment.exe
The application enables the user to specify an allocation size and the maximum amount of memory that the application should consume. For example, if we want the allocation size to be 50,000 bytes and the overall memory consumption limit to be 100MB, we would run the application as following:
C:\ADNDBIN\05Fragment 50000 100
The application proceeds to allocate memory, in chunks of the specified allocation size, until the limit is reached. After the allocations have been made, the application performs a couple of garbage collections to promote the surviving objects to generation 2 and then makes the nonpinned objects rootless, followed by another garbage collection that subsequently releases the nonpinned allocations. Let's take a look by running the application under the debugger with an allocation size of 50000 and a max memory threshold of 1GB.
After the Press any key to GC and promo to Gen1 prompt is displayed, the application has finished allocating all the memory and we can take a look at the managed heap using the DumpHeap –stat command:
0:004> !DumpHeap -stat
total 22812 objects
Statistics:
MT Count TotalSize Class Name
79119954 1 12 System.Security.Permissions.ReflectionPermission
79119834 1 12 System.Security.Permissions.FileDialogPermission
791197b0 1 12 System.Security.PolicyManager
...
...
...
791032a8 2 256 System.Globalization.NumberFormatInfo
79101fe4 6 336 System.Collections.Hashtable
7912d9bc 6 864 System.Collections.Hashtable+bucket[]
7912dd40 10 2084 System.Char[]
00395f68 564 13120 Free
7912d8f8 14 17348 System.Object[]
791379e8 1 80012 System.Runtime.InteropServices.GCHandle[]
79141f50 2 80032 System.Byte[][]
790fd8c4 2108 132148 System.String
7912dae8 20002 1000240284 System.Byte[]
Total 22812 objects
The output of the command shows a few interesting fields. Because we are looking specifically for heap fragmentation symptoms, any listed Free blocks should be carefully investigated. In our case, we seem to have 564 free blocks occupying a total size of 13120. Should we be worried about these free blocks causing heap fragmentation? Generally speaking, it is useful to look at the total size of the free blocks in comparison to the overall size of the managed heap. If the size of the free blocks is large in comparison to the overall heap size, heap fragmentation may be an issue and should be investigated further. Another important consideration to be made is that of which generation the possible heap fragmentation is occurring in. In generation 0, fragmentation is typically not a problem because the CLR heap manager can allocate using any free blocks that may be available. In generation 1 and 2 however, the only way for the free blocks to be used is by promoting objects to each respective generation. Because generation 1 is part of the ephemeral segment, which there can only be one of, generation 2 is most commonly the generation of interest when looking at heap fragmentation problems. Let's take a look at what our heap looks like by using the eeheap –gc command:
0:004> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x56192a54
generation 1 starts at 0x55d91000
generation 2 starts at 0x01c21000
ephemeral segment allocation context: none
segment begin allocated size
003a80e0 790d8620 790f7d8c 0x0001f76c(128876)
01c20000 01c21000 0282db84 0x00c0cb84(12635012)
04800000 04801000 05405ee4 0x00c04ee4(12603108)
05800000 05801000 06405ee4 0x00c04ee4(12603108)
06a50000 06a51000 07655ee4 0x00c04ee4(12603108)
07a50000 07a51000 08655ee4 0x00c04ee4(12603108)
...
...
...
4fd90000 4fd91000 50995ee4 0x00c04ee4(12603108)
50d90000 50d91000 51995ee4 0x00c04ee4(12603108)
51d90000 51d91000 52995ee4 0x00c04ee4(12603108)
52d90000 52d91000 53995ee4 0x00c04ee4(12603108)
53d90000 53d91000 54995ee4 0x00c04ee4(12603108)
54d90000 54d91000 55995ee4 0x00c04ee4(12603108)
55d90000 55d91000 5621afd8 0x00489fd8(4759512)
Large object heap starts at 0x02c21000
segment begin allocated size
02c20000 02c21000 02c23250 0x00002250(8784)
Total Size 0x3ba38e90(1000574608)
––––––––––––––––––––––––––––––
GC Heap Size 0x3ba38e90(1000574608)
The last line of the output tells us that the total GC Heap Size is right around 1GB. You may also notice that there is a rather large list of segments. Because we are allocating a rather large amount of memory, the ephemeral segment gets filled up pretty quickly and new generation 2 segments get created. We can verify this by looking at the starting address of generation 2 in the preceding output (0x01c21000) and correlating the start addresses of each segment in the segment list. Let's get back to the free blocks we saw earlier. In which generations are they located? We can find out by using the dumpheap –type Free command. An abbreviated output follows:
0:004> !DumpHeap -type Free
Address MT Size
01c21000 00395f68 12 Free
01c2100c 00395f68 24 Free
01c24c44 00395f68 12 Free
01c24c50 00395f68 12 Free
01c24c5c 00395f68 6336 Free
01e299d0 00395f68 12 Free
0202a6f4 00395f68 12 Free
0222b418 00395f68 12 Free
0242c13c 00395f68 12 Free
0262ce60 00395f68 12 Free
04801000 00395f68 12 Free
0480100c 00395f68 12 Free
04a01d30 00395f68 12 Free
04c02a54 00395f68 12 Free
04e03778 00395f68 12 Free
0500449c 00395f68 12 Free
052051c0 00395f68 12 Free
05801000 00395f68 12 Free
0580100c 00395f68 12 Free
05a01d30 00395f68 12 Free
05c02a54 00395f68 12 Free
05e03778 00395f68 12 Free
0600449c 00395f68 12 Free
062051c0 00395f68 12 Free
06a51000 00395f68 12 Free
06a5100c 00395f68 12 Free
06c51d30 00395f68 12 Free
06e52a54 00395f68 12 Free
07053778 00395f68 12 Free
0725449c 00395f68 12 Free
074551c0 00395f68 12 Free
07a51000 00395f68 12 Free
07a5100c 00395f68 12 Free
07c51d30 00395f68 12 Free
07e52a54 00395f68 12 Free
08053778 00395f68 12 Free
0825449c 00395f68 12 Free
084551c0 00395f68 12 Free
08a51000 00395f68 12 Free
08a5100c 00395f68 12 Free
08c51d30 00395f68 12 Free
08e52a54 00395f68 12 Free
09053778 00395f68 12 Free
0925449c 00395f68 12 Free
094551c0 00395f68 12 Free
09a51000 00395f68 12 Free
09a5100c 00395f68 12 Free
09c51d30 00395f68 12 Free
09e52a54 00395f68 12 Free
0a053778 00395f68 12 Free
0a25449c 00395f68 12 Free
0a4551c0 00395f68 12 Free
0aee1000 00395f68 12 Free
0aee100c 00395f68 12 Free
0b0e1d30 00395f68 12 Free
0b2e2a54 00395f68 12 Free
0b4e3778 00395f68 12 Free
...
...
...
55192a54 00395f68 12 Free
55393778 00395f68 12 Free
5559449c 00395f68 12 Free
557951c0 00395f68 12 Free
55d91000 00395f68 12 Free
55d9100c 00395f68 12 Free
55f91d30 00395f68 12 Free
56192a54 00395f68 12 Free
02c21000 00395f68 16 Free
02c22010 00395f68 16 Free
02c23020 00395f68 16 Free
02c23240 00395f68 16 Free
total 564 objects
Statistics:
MT Count TotalSize Class Name
00395f68 564 13120 Free
Total 564 objects
By looking at the address of each of the free blocks and correlating the address to the segments from the eeheap command, we can see that a great majority of the free objects reside in generation 2. With a total free size of 13120 in a heap that is right around 1GB in size, the fragmentation now is only a small fraction of one percent. Nothing to worry about (yet). Let's resume the application and keep pressing any key when prompted until you see the Press any key to exit prompt. At that point, break into the debugger and again run the DumpHeap –stat command to get another view of the heap:
0:004> !DumpHeap -stat
total 22233 objects
Statistics:
MT Count TotalSize Class Name
79119954 1 12 System.Security.Permissions.ReflectionPermission
79119834 1 12 System.Security.Permissions.FileDialogPermission
791197b0 1 12 System.Security.PolicyManager
00113038 1 12 Advanced.NET.Debugging.Chapter5.Fragment
791052a8 1 16 System.Security.Permissions.UIPermission
79117480 1 20 System.Security.Permissions.EnvironmentPermission
791037c0 1 20 Microsoft.Win32.SafeHandles.SafeFileMappingHandle
79103764 1 20 Microsoft.Win32.SafeHandles.SafeViewOfFileHandle
...
...
...
7912d8f8 12 17256 System.Object[]
791379e8 1 80012 System.Runtime.InteropServices.GCHandle[]
79141f50 2 80032 System.Byte[][]
790fd8c4 2101 131812 System.String
00395f68 10006 496172124 Free
7912dae8 10002 500120284 System.Byte[]
Total 22233 objects
This time, we can see that the amount of free space has grown considerably. From the output, there are 10006 instances of free blocks occupying a total of 496172124 bytes of memory. To find out how this total amount correlates to our overall heap size, we once again use the eeheap –gc command:
0:004> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x55d9100c
generation 1 starts at 0x55d91000
generation 2 starts at 0x01c21000
ephemeral segment allocation context: none
segment begin allocated size
003a80e0 790d8620 790f7d8c 0x0001f76c(128876)
01c20000 01c21000 02821828 0x00c00828(12585000)
04800000 04801000 053f9b88 0x00bf8b88(12553096)
...
...
...
54d90000 54d91000 55989b88 0x00bf8b88(12553096)
55d90000 55d91000 562190b0 0x004880b0(4751536)
Large object heap starts at 0x02c21000
segment begin allocated size
02c20000 02c21000 02c23240 0x00002240(8768)
Total Size 0x3b6725f4(996615668)
––––––––––––––––––––––––––––––
GC Heap Size 0x3b6725f4(996615668)
The total GC heap size is reported as 996615668 bytes. Overall, we can say that the heap is approximately 50% fragmented. This can easily be verified by looking at the verbose output of the DumpHeap command:
0:004> !DumpHeap
Address MT Size
...
...
...
55ff381c 7912dae8 50012
55fffb78 00395f68 50012 Free
5600bed4 7912dae8 50012
56018230 00395f68 50012 Free
5602458c 7912dae8 50012
560308e8 00395f68 50012 Free
5603cc44 7912dae8 50012
56048fa0 00395f68 50012 Free
560552fc 7912dae8 50012
56061658 00395f68 50012 Free
5606d9b4 7912dae8 50012
56079d10 00395f68 50012 Free
5608606c 7912dae8 50012
560923c8 00395f68 50012 Free
5609e724 7912dae8 50012
560aaa80 00395f68 50012 Free
560b6ddc 7912dae8 50012
560c3138 00395f68 50012 Free
560cf494 7912dae8 50012
560db7f0 00395f68 50012 Free
560e7b4c 7912dae8 50012
560f3ea8 00395f68 50012 Free
56100204 7912dae8 50012
5610c560 00395f68 50012 Free
...
...
...
From the output, we can see that a pattern has emerged. We have a block of size 50012 that is allocated and in use followed by a free block of the same size that is considered free. We can use the DumpObj command on the allocated object to find out more details:
0:004> !DumpObj 5606d9b4
Name: System.Byte[]
MethodTable: 7912dae8
EEClass: 7912dba0
Size: 50012(0xc35c) bytes
Array: Rank 1, Number of elements 50000, Type Byte
Element Type: System.Byte
Fields:
None
This object is a byte array, which corresponds to the allocations that our application is creating. How did we end up with such an allocation pattern (allocated, free, allocated, free) to begin with? We know that the garbage collector should perform compacting and coalescing to avoid this scenario. One of the situations that can cause the garbage collector not to compact and coalesce is if there are objects on the heap that are pinned (i.e., nonmoveable). To find out if that is indeed the case in our application, we need to see if there are any pinned handles in the process. We can utilize the GCHandles command to get an overview of handle usage in the process:
0:004> !GCHandles
GC Handle Statistics:
Strong Handles: 15
Pinned Handles: 10004
Async Pinned Handles: 0
Ref Count Handles: 0
Weak Long Handles: 0
Weak Short Handles: 1
Other Handles: 0
Statistics:
MT Count TotalSize Class Name
790fd0f0 1 12 System.Object
790feba4 1 28 System.SharedStatics
790fcc48 2 48 System.Reflection.Assembly
790fe17c 1 72 System.ExecutionEngineException
790fe0e0 1 72 System.StackOverflowException
790fe044 1 72 System.OutOfMemoryException
790fed00 1 100 System.AppDomain
790fe704 2 112 System.Threading.Thread
79100a18 4 144 System.Security.PermissionSet
790fe284 2 144 System.Threading.ThreadAbortException
7912d8f8 4 8744 System.Object[]
7912dae8 10000 500120000 System.Byte[]
Total 10020 objects
The output of GCHandles tells us that we have 10004 pinned handles. Further more, in the statistics section, we can see that 10,000 of those handles are used to pin byte arrays. At this point, we are almost there and can do a quick code review that shows that half of the byte array allocations made in the application are explicitly pinned, causing the heap to get fragmented.
Excessive or prolonged pinning is one of the most common reasons behind fragmentation of the managed heap. If pinning is necessary, the developer must ensure that pinning is short lived in order not to interfere too much with the garbage collector.
How Much Is Too Much?
In our preceding example, initially, the heap fragmentation was a fraction of one percent. At that point, we really didn't have to pay too much attention to it as it was too small to concern us. Later, we noticed that the fragmentation grew to 50%, which caused an in-depth investigation to figure out the reason for it. Is there a magical percentage of when one should start worrying? There is no hard number, but generally speaking if the heap is between 10% and 30% fragmented, due diligence should be exercised to ensure that it is not a long-running problem.
In the preceding example, we looked at fragmentation as it relates to the managed heap. It is also possible to encounter situations where the virtual memory managed by the Windows virtual memory manager gets fragmented. In those cases, the CLR heap manager may not be able to grow its heap (i.e., allocate new segments) to accommodate allocation requests. The address command can be used to get in-depth information on the systems virtual memory state.
Advanced .NET Debugging: Managed Heap and Garbage Collection(转载,托管堆查内存碎片问题解决思路)的更多相关文章
- .NET:CLR via C#The Managed Heap and Garbage Collection
Allocating Resources from the Managed Heap The CLR requires that all objects be allocated from the m ...
- Understanding the managed heap
Understanding the managed heap Another common problem faced by many Unity developers is the unexpe ...
- ES 内存使用和GC指标——主节点每30秒会去检查其他节点的状态,如果任何节点的垃圾回收时间超过30秒(Garbage collection duration),则会导致主节点任务该节点脱离集群。
摘录自:http://blog.csdn.net/yangwenbo214/article/details/74000458 内存使用和GC指标 在运行Elasticsearch时,内存是您要密切监控 ...
- Java Garbage Collection Basics--转载
原文地址:http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html Overview Purpose ...
- How Garbage Collection Really Works
Java Memory Management, with its built-in garbage collection, is one of the language's finest achiev ...
- JVM学习二:垃圾收集(Garbage Collection,GC)机制
JVM的GC分为两个主要部分,第一部分是判断对象是否已死(堆内存的垃圾回收占主要部分,方法区(metaspace)的内存回收在最新的官方文档中未给出详细解释,暂时不做讨论范围),第二部分是对内存区进行 ...
- 2.5 – Garbage Collection 自动垃圾回收 Stop-the-world vs. incremental vs. concurrent 垃圾回收策略
2.5 – Garbage Collection 自动垃圾回收 Lua 5.3 Reference Manual http://www.lua.org/manual/5.3/manual.html# ...
- Fundamentals of Garbage Collection
[Fundamentals of Garbage Collection] 1.Reclaims objects that are no longer being used, clears their ...
- C# - Garbage Collection
The .NET Framework's garbage collector manages the allocation and release of memory for your appl ...
随机推荐
- DHCP与PPPOE 区别
1.静态IP的方式,如果是占用一个INTERNET的IP的话,上网都是很贵的,当然这个也是最方便的,开机就能上网,不用做任何拨号或者认证的过程.2.PPPOE,只是多了一个获得IP的过程,一旦获得了I ...
- Sql Server两个数据库中有一张表的结构一样,怎么快速将一张表中的数据复制到另一个表中
1,下面这句会把表2数据删除,然后把表1复制到表一,两表内容一样 SELECT * into 表2 FROM 表1 2,这句只追加,不删除表2的数据 insert into 表1 select * f ...
- Android Gradle 隐形依赖的奇怪案例
相信 Android 开发者都有在 Android Studio 中升级 compileSdkVersion 的经历,这个时候如果你使用了 support 包,并同时升级,那么可能会出现一个错误提示. ...
- 【离散数学】 SDUT OJ 传递闭包 && memset 使用注意事项
传递闭包 Time Limit: 1000 ms Memory Limit: 65536 KiB Submit Statistic Problem Description 已知有n头牛,m次战斗关系, ...
- css grid学习笔记
仅为自己用而收藏罢了 w3c官方文档 https://www.w3.org/TR/css-grid-1/#grid-items w3cplus(zhongwenban ) 大漠博主的系列文章 基础知识 ...
- 用qt creator创建可继承ui类
https://jingyan.baidu.com/article/5d368d1efa2dd73f60c05786.html 用qt creator创建可继承ui类 听语音 | 浏览:1657 | ...
- vue 阻止冒泡弹窗小案例( 知识点:@click.stop=''")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Android 数据库框架GreenDao实战使用
1.添加记录(SQLite 增) 2.删除记录(SQLite 删) 3.修改记录(SQLite 改) 4.查询记录(SQLite 查) <1> DAO查询 <2>QueryBu ...
- php 实现无限极分类
原始数据 $array = array( array('id' => 1, 'pid' => 0, 'n' => '河北省'), array('id' => 2, 'pid' ...
- 在OnActionExecuted 获取请求参数的值(包含类类型)
1.在OnActionExecuting里 获取请求参数的值 比较简单 /// <summary> /// 获取首参数的值 /// </summary> /// <par ...