Advanced. NET debugging:managed Heap and Garbage Collection (reprinted, managed heap check memory fragmentation problem solving ideas)

Source: Internet
Author: User

Original address: 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 is arranged And interleaved on the managed heap in such a a-they can cause problems in applications that surface as OutOfMemory Exceptions In reality, enough memory was 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'll take a look at an example the can cause heap fragmentation to occur and how we can use the debug Gers to identify that a heap fragmentation are 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 is found in the following folders:

    • Source Code: C:\ADND\Chapter5\Fragment
    • Binary: C:\ADNDBin\05Fragment.exe

The application enables the user to specify a allocation size and the maximum amount of memory that the application Shoul D consume. For example, if we want the allocation size to being 50,000 bytes and the overall memory consumption limit to be 100MB, we wo Uld 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 has been made, the application performs a couple of garbage collections to promote the surviving OB Jects to Generation 2 and then makes the nonpinned objects rootless, followed by another garbage collection that Subsequen tly 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 are displayed, the application have 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 objectsstatistics:mt Count totalsize Class Name79119954 1 System.Security.Permissions.ReflectionPermission79119834 1 System.Security.Permissions.FileDialogPe Rmission791197b0 1 System.Security.PolicyManager ..... 791032a8 2 System.Globalization.NumberFormatInfo79101fe4 6 336 System.Collections.Hash TABLE7912D9BC 6 864 system.collections.hashtable+bucket[]7912dd40 2084 system.char[]
    
     00395f68 564 13120 free   7912d8f8 + 17348 system.object[] 
      79 1379e8 1 80012 system.runtime.interopservices.gchandle[]   79141f50 2 80032 syste M.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 is looking specifically for heap fragmentation symptoms, any listed FreeBlocks should be carefully investigated. We seem to564Free blocks occupying a total size of13120. Should we are 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 Aged heap. If the size of the free blocks are large in comparison to the overall heap size, the heap fragmentation could be a issue and SHO Uld be investigated further. Another important consideration to be made are that of which generation the possible heap fragmentation are occurring in. In generation 0, fragmentation are typically not a problem because the CLR heap manager can allocate using any free blocks That could be available. In Generation 1 and 2 However, the-the-only-for-the-free blocks-to-be used are by promoting objects to each respective gene Ration. Because Generation 1 is part of the ephemeral segment, which there can only be one of, Generation 2 are most commonly the G Eneration of interest when looking at heap fragmentation problems. Let's take a look at the what we heap looks like by using thE EEHEAP–GCCommand

0:004>!EEHEAP-GCNumber of GC Heaps:1generation 0 starts at 0x56192a54generation 1 starts @ 0x55d91000generation 2 starts at 0X01C21000EP Hemeral segment allocation Context:none segment begin allocated Size003a80e0 790d8620 790f7d8c 0x0001f76c (128876) 01c20000 01c21000 0282db84 0x00c0cb84 (12635012) 04800000 04801000 05405ee4 0x00c04ee4 (12603108) 05800000 05801000 06405e E4 0x00c04ee4 (12603108) 06a50000 06a51000 07655ee4 0x00c04ee4 (12603108) 07a50000 07a51000 08655ee4 0x00c04ee4 (12603108) ......... 4fd90000 4fd91000 50995ee4 0x00c04ee4 (12603108) 50d90000 50d91000 51995ee4 0x00c04ee4 (12603108) 51d90000 51d91000 52995e E4 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 size02c20000 02c21000 02c23250 0x00002250 (8784) Total Size 0x3ba38e90 (10005746 08) –––––––––––––––––––––––––––––– GC Heap Size 0x3ba38e90 (1000574608)

The last line of the output tells us, the total GC Heap Size was right around 1GB. Also notice that there is a rather large list of segments. Because We is allocating a rather large amount of memory, the ephemeral segment gets filled up pretty quickly and new Gen Eration 2 segments get created. We can verify the looking at the starting address of Generation 2 in the preceding output (0x01c21000) and Co Rrelating the start addresses of each segment in the segment list. Let's get back to the free blocks we saw earlier. In which generations is they located? We can find out by using the dumpheap–type free command. An abbreviated output follows:

0:004>! Dumpheap-type Free Address MT size01c21000 00395f68 free01c2100c 00395f68 free01c24c44 00395f68 01C24C50 00395f68 free01c24c5c 00395f68 6336 free01e299d0 00395f68 1 free0202a6f4 00395f68        2 free0222b418 00395f68 free0242c13c 00395f68 free0262ce60 00395f68 (Free04801000 00395f68) free0480100c 00395f68 free04a01d30 00395f68 free04c02a54 00395f68 00395  f68 free0500449c 00395f68-free052051c0 00395f68-Free05801000 00395f68 00395f68 free05a01d30 00395f68-free05c02a54 00395f68-free05e03778 00395f68 00449c 00395f68 free062051c0 00395f68 free06a51000 00395f68 12 free06a5100c 00395f68        Free06c51d30 00395f68 free06e52a54 00395f68 Free07053778 00395f68 00395 free074551c0f68 free07a51000 00395f68-free07a5100c 00395f68-Free07c51d30 00395f68 00395f68 Free08053778 00395f68-free0825449c 00395f68-free084551c0 00395f68 a51000 00395f68 free08a5100c 00395f68 free08c51d30 00395f68 12 free08e52a54 00395f68        Free09053778 00395f68 free0925449c 00395f68 free094551c0 00395f68 free09a5100c 00395f68 free09c51d30 00395f68 free09e52a54 00395f68 8 free0a25449c 00395f68 free0a4551c0 00395f68 free0aee1000 00395f68 0 free0aee100c 0395f68 free0b0e1d30 00395f68-free0b2e2a54 00395f68-free0b4e3778 00395f68 .... ..... 55192a54 00395f68 Free55393778 00395f68 free5559449c 00395f68 1 free557951c0 00395f68 2 free55d91000 00395f68 free55d9100c 00395f68-free55f91d30 00395f68-free56192a54 00395f68 0 00395f68-free02c22010 00395f68 free02c23020 00395f68 (free02c23240 00395f68) freet Otal 564 objectsstatistics:mt Count totalsize Class name00395f68 564 13120 freetotal 564 Obje Cts

By looking at the address of the blocks and correlating the address to the segments from the eeheap command, we can see this a great majority of the free objects reside in Generation 2. With a total free size of 13120 in a heap that's right around 1GB in size, and the fragmentation now was 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 do see the Press any key to exit Prom Pt. At a, break into the debugger and again run the dumpheap–stat command to get another view of the heap:

0:004>! Dumpheap-statTotal 22233 objectsstatistics:mt Count totalsize Class Name79119954 1 System.Security.Pe Rmissions.            ReflectionPermission79119834 1 System.Security.Permissions.FileDialogPermission791197b0 1        System.Security.PolicyManager00113038 1 Advanced.NET.Debugging.Chapter5.Fragment791052a8 1 System.Security.Permissions.UIPermission79117480 1 SYSTEM.SECURITY.PERMISSIONS.E            NVIRONMENTPERMISSION791037C0 1 Microsoft.Win32.SafeHandles.SafeFileMappingHandle79103764 1 Microsoft.Win32.SafeHandles.SafeViewOfFileHandle ..... 7912d8f8 17256 system.object[]791379e8 1 80012 system.runtime.interopservices.gchandle[]79141F50 2 80032 system.byte[][]790fd8c4 2101 131812 System.String00395f68 10006 496172124 Free7912dae8 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 is 10006 instances of free blocks occupying a total of 496172124 bytes of memory . To find the amount correlates to our overall heap size, we once again use the EEHEAP–GC command:

!EEHEAP-GC Number of GC Heaps:1generation 0 starts at 0x55d9100cgeneration 1 starts @ 0x55d91000generation 2 starts at 0X01C21000EP Hemeral segment allocation Context:none segment    begin allocated     size003a80e0 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     size02c20000 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 is verified by looking at the verbose output of the dumpheap command:

 0:004> ! Dumpheap  Address MT Size ..... 55ff381c 7912dae8 5001255fffb78 00395f68 50012 free5600bed4 7912dae8 5001256018230 00395f68 50012 Free5602  458c 7912dae8 50012560308e8 00395f68 50012 free5603cc44 7912dae8 5001256048fa0 00395f68 50012 FREE560552FC     7912dae8 5001256061658 00395f68 50012 free   5606d9b4   7912dae8 5001256079d10 00395f68     50012 free5608606c 7912dae8 50012560923c8 00395f68 50012 free5609e724 7912dae8 50012560aaa80 00395f68 50012 FREE560B6DDC 7912dae8 50012560c3138 00395f68 50012 free560cf494 7912dae8 50012560db7f0 00395f68 5001 2 free560e7b4c 7912dae8 50012560f3ea8 00395f68 50012 Free56100204 7912dae8 500125610c560 00395f68 50012 Fr EE ..... 

From the output, we can see that a pattern has emerged. We have a block of size 50012 , which is allocated and on use followed by a free block of the same size, which is cons idered free. We can use the dumpobj command in the allocated object to find out more details:

! DumpObj 5606d9b4system.byte[]methodtable:7912dae8eeclass:7912dba0size:50012 (0xc35c) BytesArray: Rank 1, number of elements 50000, Type byteelement Type:System.ByteFields:None

This object was a byte array, which corresponds to the allocations, we application is creating. How do we end up with such a allocation pattern (allocated, free, allocated, free) to begin with? We know 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 be objects on the heap That is pinned (i.e., nonmoveable). To find an if that's indeed the case in our application, we need to see if there be any pinned handles in the process. We can utilize the gchandles command to get a overview of handle usage in the process:

 0:004> ! Gchandles  GC Handle statistics:strong handles:15   Pinned handles:10004   Async Pinned Handles:0ref Count Handles:0weak Long handles:0weak short handles:1other handles:0statistics:mt Count Tot        Alsize Class name790fd0f0 1 system.object790feba4 1 system.sharedstatics790fcc48        2 System.Reflection.Assembly790fe17c 1 system.executionengineexception790fe0e0           1 system.stackoverflowexception790fe044 1 system.outofmemoryexception790fed00 1 2 system.appdomain790fe704 System.Threading.Thread79100a18 4 144 System. security.permissionset790fe284 2 144 System.Threading.ThreadAbortException7912d8f8 4 8744 S Ystem. Object[]   7912dae8 10000 500120000 system.byte[]   Total 10020 objects 

The output of Gchandles tells us we have 10004 pinned handles. Further more, under the Statistics section, we can see that the those of handles is used to pin byte arrays. At this point, we is almost there and can do a quick code review that shows that half of the byte array allocations made In the application is 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 this 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 is a fraction of one percent. At the point, we really didn ' t has to pay too much attention to it as it is too small to concern us. Later, we noticed that the fragmentation grew to 50%, which caused a 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 was between 10% and 30% fragmented, due diligence should be exe Rcised to ensure that it's 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 FR Agmented. In those cases, the CLR heap manager May is able to grow it heap (i.e., allocate new segments) to accommodate Allocat Ion requests. The Address command can be used-get in-depth information on the systems virtual memory state.

Advanced. NET debugging:managed Heap and Garbage Collection (reprinted, managed heap check memory fragmentation problem solving ideas)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.