Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit

재미있는 글이 있군요. ^^

Running with Server GC in a Small Container Scenario Part 1 – Hard Limit for the GC Heap
; https://devblogs.microsoft.com/dotnet/running-with-server-gc-in-a-small-container-scenario-part-1-hard-limit-for-the-gc-heap/

위의 글에 보면 COMPlus_GCHeapHardLimit 옵션이 나오는데요, 이게 Java의 Xmx와 유사한 역할을 합니다. 가볍게 테스트를 해볼까요? ^^

.NET Core 3.1 + Debug 빌드로 다음의 코드를 마련하고,

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            CallGC();
            ShowGCInfo();
            Console.WriteLine(Environment.NewLine);
        }

        static void CallGC()
        {
            GC.Collect(2, GCCollectionMode.Forced, true);
        }

        static void ShowGCInfo()
        {
            var info = GC.GetGCMemoryInfo();

            Console.WriteLine($"HeapSizeBytes: {info.HeapSizeBytes}");
            Console.WriteLine($"TotalAvailableMemoryBytes: {info.TotalAvailableMemoryBytes}");
            Console.WriteLine($"FragmentedBytes: {info.FragmentedBytes}");
            Console.WriteLine($"HighMemoryLoadThresholdBytes: {info.HighMemoryLoadThresholdBytes}");
            Console.WriteLine($"MemoryLoadBytes: {info.MemoryLoadBytes}");
        }
    }
}

이렇게 max 값을 주면,

c:\temp> set COMPlus_GCHeapHardLimit=33000

c:\temp> ConsoleApp2.exe
Failed to create CoreCLR, HRESULT: 0x8007000E

0x8007000E (Not enough memory resources are available to complete this) 오류가 발생합니다. 위에서 COMPlus_GCHeapHardLimit은 16진수 값을 받아들이는데, 따라서 0x33000 == 208,986 바이트로는 메모리 부족이 발생한 것입니다.

여기서 조금 늘려 실행하면,

c:\temp> set COMPlus_GCHeapHardLimit=33100

c:\temp> ConsoleApp2.exe
HeapSizeBytes: 57096
TotalAvailableMemoryBytes: 209152
FragmentedBytes: 120
HighMemoryLoadThresholdBytes: 61603382476
MemoryLoadBytes: 29432727183

잘 실행이 됩니다. 위의 결과를 보면 COMPlus_GCHeapHardLimit의 설정값과 TotalAvailableMemoryBytes의 값이 동일한데요, 실제로 공식 문서에는,

GCMemoryInfo.TotalAvailableMemoryBytes Property
; https://learn.microsoft.com/en-us/dotnet/api/system.gcmemoryinfo.totalavailablememorybytes

TotalAvailableMemoryBytes가 GC Heap의 "Free"를 나타내진 않고 현재 프로세스에서 최대 사용할 수 있는 메모리의 크기를 나타낸다고 쓰여있습니다.

This property value will be the value of the COMPlus_GCHeapHardLimit environment variable, or the Server.GC.HeapHardLimit value in runtimeconfig.json, if either is set.


그건 그렇고, Running with Server GC in a Small Container Scenario Part 1 – Hard Limit for the GC Heap 글에 보면, 닷넷 프로세스에서 사용하는 메모리를 크게 3분류로 나누는데,

  1. 이미 할당된 GC Heap 메모리와, 향후 GC가 사용할 목적으로 할당된 native memory
  2. 닷넷 런타임에 의해 사용되는 native memory, 예를 들어 IL 코드를 번역한 기계어가 위치하는 jitted code heap
  3. 닷넷 런타임 이외의 코드에서 할당된 메모리, 예를 들어 Pinvoke로 호출한 C/C++ DLL에서 할당한 메모리

TotalAvailableMemoryBytes는 과연 어떤 메모리에 대한 상한을 제한하는 것일까요? 일단 위의 메모리 중 당연히 3번은 제외했을 것이고, 그렇다면 1번만 해당할까요? 1, 2번 모두 해당할까요? 문서에 보면, "Specifies the maximum commit size, in bytes, for the GC heap and GC bookkeeping"라고 나오는 걸로 봐서는 1번만 포함하는 것이 맞습니다.

여기서 유의할 것은 "GC heap"과 함께 "GC가 예약하는 크기"가 포함된다는 점입니다. 이런 점은 간단하게 테스트로 확인할 수 있는데요, 위의 출력 결과를 보면, TotalAvailableMemoryBytes == 209152 값에서 현재 HeapSizeBytes가 57096이니까, 대충 152,056 바이트 여유 공간이 남습니다. 그런데, 다음과 같이 그에 한참 못 미치는 15,000 바이트 정도를 소비하는 byte 버퍼를 생성해 테스트하면,

static byte[] buffer = null;

static void Main(string[] args)
{
    buffer = new byte[15_000];
    
    CallGC();
    ShowGCInfo();
    Console.WriteLine(Environment.NewLine);
}

/* 실행 결과
HeapSizeBytes: 72144
TotalAvailableMemoryBytes: 209152
FragmentedBytes: 120
HighMemoryLoadThresholdBytes: 61603382476
MemoryLoadBytes: 29432727183


Out of memory.
*/

HeapSizeBytes는 15,048 바이트 정도 늘어났지만 저렇게 "Out of memory"가 프로그램의 말미에 발생하고 있습니다. 아마도 저 순간에 예약을 늘리는 코드가 동작했기 때문이 아닌가... 추측을 해봅니다.

당연하겠지만, native 메모리를 사용하는 것은 제약에 포함이 안 되므로 아래의 코드는 잘 실행됩니다.

// 아래의 제약에서도 정상 실행
// set COMPlus_GCHeapHardLimit=33100

static void Main(string[] args)
{
    Marshal.AllocCoTaskMem(1024 * 1024 * 512);
    CallGC();
    ShowGCInfo();
    Console.WriteLine(Environment.NewLine);
}




해당 글에 보면, HeapHardLimit을 runtimeconfig.json에도 설정할 수 있다고 나오는데요, 그러면서 값을 "Server.GC.HeapHardLimit"라고 소개합니다. 하지만, 실제로 문서를 보면 "System.GC.HeapHardLimit"가 맞습니다.

Runtime configuration options for garbage collection
 - Heap limit
; https://learn.microsoft.com/en-us/dotnet/core/runtime-config/garbage-collector#heap-limit

그래서 이렇게 설정할 수 있습니다.

// runtimeconfig.template.json
// Host Configuration Knobs

{
    "configProperties": {
        "System.GC.HeapHardLimit": 209152
    }
}

유의할 점은, 환경 변수에서는 16진수로 값을 설정했지만 위의 json에서는 10진수로 설정한다는 것입니다.

또한, HeapHardLimit와 함께 "Heap limit percent"도 제공하고 있으니 관심 있으신 분은 문서를 읽어보시길. ^^

Heap limit percent
; https://learn.microsoft.com/en-us/dotnet/core/runtime-config/garbage-collector#heap-limit-percent

참고로, Running with Server GC in a Small Container Scenario Part 1 – Hard Limit for the GC Heap 글에서 container가 자주 언급되는데, 아마도 이런 설정들은 근래의 container 환경이 대두됨에 따라 추가된 듯합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/3/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13573정성태3/5/20241558닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241633닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241598닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241622닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241537닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241601닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241613오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241626오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241464닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241607Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241625디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241628오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241739닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241743디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242620오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241802닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241569Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241634Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241943닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241704VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241726닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241680닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242009닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242101Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242473개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242300개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...