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.

时间: 2024-12-17 15:48:39

Advanced .NET Debugging: Managed Heap and Garbage Collection(转载,托管堆查内存碎片问题解决思路)的相关文章

Java Garbage Collection Basics--转载

原文地址:http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html Overview Purpose This tutorial covers the basics of how Garbage Collection works with the Hotspot JVM. Once you have learned how the garbage collector functions, lear

Tuning Java Garbage Collection for Spark Applicati

This is a guest post from our friends in the SSG STO Big Data Technology group at Intel. Join us at the Spark Summit to hear from Intel and other companies deploying Spark in production.  Use the code Databricks20 to receive a 20% discount! Spark is

Fundamentals of Garbage Collection

[Fundamentals of Garbage Collection] 1.Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do

C# - Garbage Collection

 The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap. As long as address spac

从ASP.NET Core 3.0 preview 特性,了解CLR的Garbage Collection

前言 在阅读这篇文章:Announcing Net Core 3 Preview3的时候,我看到了这样一个特性: Docker and cgroup memory Limits We concluded that the primary fix is to set a GC heap maximum significantly lower than the overall memory limit as a default behavior. In retrospect, this choice

[Java] 垃圾回收机制 ( Garbage Collection ) 简介

自动垃圾回收( Automatic Garbage Collection ) 自动垃圾回收,是指在堆(Heap)内存上分辨哪些对象还在被使用,哪些对象没有被使用,并清除没有被使用的对象.所以,这里的垃圾实际上是指,在内存中,无法再被使用没有存在的价值的但还占据内存空间的对象. C 语言的内存分配.回收是需要手动完成的,但在 Java 中,回收内存是由垃圾回收器自动完成的. 垃圾回收分为两步骤:1.标记,2.删除.删除垃圾有两种情况,a. 常规删除,b. 带压缩的删除. 第 1 步. 标记 ( M

GC(Garbage Collection)垃圾回收机制

1.在垃圾回收器中,程序员没有执行权,只有通知它的权利. 2.程序员可以通过System.gc().通知GC运行,但是Java规范并不能保证立刻运行. 3.finalize()方法,是java提供给程序员用来释放对象或资源的办法,但是尽量少用. 一.GC的介绍 GC的全称是Garbage Collection (垃圾收集) 在GC中,垃圾所指的是程序在运行过程中,会产生出一些无用的对象,或者说是已经被弃用的对象,而这些对象会占用着一部分的内存空间,如果长时间不去回收这些内存空间,那么最终会导致O

垃圾回收(garbage collection)介绍

 垃圾回收用来实现内存的自动管理(automatic management),区别于人工管理(manual management).人工管理内存容易出现的问题: 1)悬垂指针,dangling pointer 2)重复回收,Double free 3)内存泄露,memory leak 历史 垃圾回收的概念及技术由John McCarthy于1959年发明,应用于List语言中.1959年,计算机科学应该还处于探索.萌芽阶段,但这位大神已经发明了垃圾回收,大神就是大神. 策略 目前的垃圾回收策

深入理解Java中的Garbage Collection

前提 最近由于系统业务量比较大,从生产的GC日志(结合Pinpoint)来看,需要对部分系统进行GC调优.但是鉴于以往不是专门做这一块,但是一直都有零散的积累,这里做一个相对全面的总结.本文只针对HotSpot VM也就是Oracle Hotspot VM或者OpenJDK Hotspot VM,版本为Java8,其他VM不一定适用. 什么是GC(Garbage Collection) Garbage Collection可以翻译为"垃圾收集" -- 一般主观上会认为做法是:找到垃圾,