Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 12개 있습니다.)
.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes
; https://www.sysnet.pe.kr/2/0/11838

.NET Framework: 816. (번역글) .NET Internals Cookbook Part 2 - GC-related things
; https://www.sysnet.pe.kr/2/0/11869

.NET Framework: 818. (번역글) .NET Internals Cookbook Part 3 - Initialization tricks
; https://www.sysnet.pe.kr/2/0/11871

.NET Framework: 819. (번역글) .NET Internals Cookbook Part 4 - Type members
; https://www.sysnet.pe.kr/2/0/11872

.NET Framework: 820. (번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers
; https://www.sysnet.pe.kr/2/0/11873

.NET Framework: 821. (번역글) .NET Internals Cookbook Part 6 - Object internals
; https://www.sysnet.pe.kr/2/0/11874

.NET Framework: 822. (번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others
; https://www.sysnet.pe.kr/2/0/11876

.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas
; https://www.sysnet.pe.kr/2/0/11877

.NET Framework: 824. (번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff
; https://www.sysnet.pe.kr/2/0/11878

.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others
; https://www.sysnet.pe.kr/2/0/11879

.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles
; https://www.sysnet.pe.kr/2/0/11882

.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
; https://www.sysnet.pe.kr/2/0/11891




(번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff

이번에도 .NET Internals Cookbook 시리즈의 9번째 글을 번역한 것입니다.

.NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff
; https://blog.adamfurmanek.pl/2019/04/13/net-internals-cookbook-part-9/





59. finalizer에서 예외가 발생하거나 무한 루프에 빠진다면?

다음의 코드로 finalizer에서 예외를 발생시키면,

using System;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Testing Foo");

            var foo = new Foo();
            foo = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.WriteLine("Testing Bar");

            var bar = new Bar();
            bar = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.WriteLine("Done!");
        }
    }
}

class Foo
{
    ~Foo()
    {
        Console.WriteLine("Good destructor");
    }
}

class Bar
{
    ~Bar()
    {
        Console.WriteLine("Destructor with exception");
        throw new Exception();
    }
}

/* 출력 결과
Testing Foo
Good destructor
Testing Bar
Destructor with exception

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
   at Bar.Finalize() in C:\temp\q59\ConsoleApp1\Program.cs:line 41
*/

프로그램이 종료하는 것을 볼 수 있습니다. 이는 Object.Finalize Method 문서에 다음과 같이 명시되어 있습니다.

If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try/finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources.


저도 관련된 글을 쓴 적이 있습니다. ^^

windbg 분석 사례 - 종료자(Finalizer)에서 예외가 발생한 경우 비정상 종료(Crash) 발생
; https://www.sysnet.pe.kr/2/0/11732

그렇다면, Finalizer에서 무한 루프가 발생하면 어떻게 될까요?

using System;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Testing Foo");

            var foo = new Foo();
            foo = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.WriteLine("Testing Bar");

            var bar = new Bar();
            bar = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.WriteLine("Done!");
        }
    }
}

class Foo
{
    ~Foo()
    {
        Console.WriteLine("Good destructor");
    }
}

class Bar
{
    ~Bar()
    {
        Console.WriteLine("Destructor with infinite loop");
        while (true) { }
    }
}

/* 출력 결과
Testing Foo
Good destructor
Testing Bar
Destructor with infinite loop
*/

표면 상으로는 문제가 없는 듯하지만, 실제로는 프로그램이 진행되면서 finalizer를 구현한 객체들이 누적되면서 OOM 예외가 발생할 가능성이 높아집니다. 이에 대해서는 다음의 글에서,

windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
; https://www.sysnet.pe.kr/2/0/11803

windbg - 닷넷 응용 프로그램의 메모리 누수 분석
; https://www.sysnet.pe.kr/2/0/11808

windbg의 finalizequeue 명령어로 확인할 수 있다고 설명했습니다.





60. What is finalization queue? What is f-reachable queue?

종료 큐(finalization queue)와 F-reachable 큐에 대해서는 제 책의 "5.4.2.6 소멸자" 절을 참고하세요. ^^





61. 객체를 pinnging 한다는 의미

GC Heap에 있는 객체를 외부(Native) 코드에 전달했다고 가정해 봅니다. 그럼 외부에서 그 객체를 사용하는 동안 GC가 발동할 수도 있고 그렇게 되면 해당 객체의 위치가 바뀌게 됩니다. 하지만 외부 코드는 바뀐 객체에 대한 포인터를 모르므로 엉뚱한 위치의 데이터를 접근할 수 있습니다.

따라서 이 문제를 해결하기 위해 GC Heap에 있는 객체를 "움직이지 못하는 상태"로 고정시키는 것을 pinning이라고 합니다. 즉, 외부 코드에 GC Heap의 객체를 전달하려면 반드시 pinning시켜야만 합니다. pinning을 명시적으로 하려면 fixed 예약어GC.Alloc 메서드를 사용할 수 있습니다.





62. P/Inovke 호출은 인자를 pinning 할까?

P/Invoke 메서드가 호출되는 동안, 해당 메서드에 전달한 인자들은 자동으로 pinning 됩니다. 따라서 P/Invoke 메서드가 비동기 호출이라면 메서드 자체의 호출 이후에는 pinning이 풀리므로 비동기 작업이 완료되었을 때 문제가 발생할 수 있으므로 그런 경우에는 직접 pinning을 해야 합니다.





63. 쓰기 장벽(write barrier)이란?

이 용어에 대한 자세한 설명은 다음 질문으로 넘기고 일단 쓰기 장벽이 실제로 사용되고 있는 사례를 검토해 보겠습니다. 예를 들어 다음의 코드는 Bar 객체를 Foo 객체가 포함하고 있는 상황입니다.

using System;

namespace Program
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var foo = new Foo();
            GC.Collect();

            Console.WriteLine(GC.GetGeneration(foo));
            foo.Bar = new Bar();
            Console.ReadLine();
        }
    }
}

class Foo
{
    public Bar Bar;
}

class Bar
{
}

빌드하고 Main 메서드의 IL 코드를 보면,

// ...[생략]...
  .method public hidebysig static void  Main(string[] args) cil managed

  {
    // 
    .maxstack  2
    .locals init ([0] class Foo foo)
    .language '{3F5162F8-07C6-11D3-9053-00C04FA302A1}', '{994B45C4-E6E9-11D2-903F-00C04FA302A1}', '{5A869D0B-6611-11D3-BD2A-0000F80849BD}'
    IL_0000:  nop
    IL_0001:  newobj     instance void Foo::.ctor()
    IL_0006:  stloc.0
    IL_0007:  call       void [mscorlib]System.GC::Collect()
    IL_000c:  nop
    IL_000d:  ldloc.0
    IL_000e:  call       int32 [mscorlib]System.GC::GetGeneration(object)
    IL_0013:  call       void [mscorlib]System.Console::WriteLine(int32)
    IL_0018:  nop
    IL_0019:  ldloc.0
    IL_001a:  newobj     instance void Bar::.ctor()
    IL_001f:  stfld      class Bar Foo::Bar
    IL_0024:  call       string [mscorlib]System.Console::ReadLine()
    IL_0029:  pop
    .line 15,15 : 9,10 ''
    IL_002a:  ret
  } // end of method Program::Main

// ...[생략]...

"foo.Bar = new Bar();" 코드에 특이점이 없습니다. 하지만 이 코드를 실행 시 JIT 컴파일된 기계어로 보면 다음과 같이 clr!JIT_WriteBarrierEAX 함수가 호출되는 것을 볼 수 있습니다.

C:\Users\adafurma\source\repos\ConsoleApp3\ConsoleApp3\Program.cs @ 13:
007a04a9 b9184e5d00      mov     ecx,5D4E18h (MT: Bar)
007a04ae e8152ce2ff      call    005c30c8 (JitHelp: CORINFO_HELP_NEWSFAST)
007a04b3 8945ec          mov     dword ptr [ebp-14h],eax
007a04b6 8b4dec          mov     ecx,dword ptr [ebp-14h]
007a04b9 ff15384e5d00    call    dword ptr ds:[5D4E38h] (Bar..ctor(), mdToken: 06000002)
007a04bf 8b55f4          mov     edx,dword ptr [ebp-0Ch]
007a04c2 8b45ec          mov     eax,dword ptr [ebp-14h]
007a04c5 8d5204          lea     edx,[edx+4]
007a04c8 e8b3e2d872      call    clr!JIT_WriteBarrierEAX (7352e780)

C:\Users\adafurma\source\repos\ConsoleApp3\ConsoleApp3\Program.cs @ 14:
007a04cd e82a7e4372      call    mscorlib_ni+0xb582fc (72bd82fc) (System.Console.ReadLine(), mdToken: 06000b65)
007a04d2 8945e8          mov     dword ptr [ebp-18h],eax
007a04d5 90              nop

CLR은 왜? JIT_WriteBarrierEAX 코드를 넣은 걸까요? 이어지는 다음의 질문에서 알아봅니다.





64. Card 테이블? Brick 테이블?

이전 글에서 "Bar 객체를 Foo 객체가 포함"하고 있는 상황이라고 했는데 예전에 제가 썼던 다음의 글에서 이와 관련해 card table을 설명했었습니다.

.NET GC - 하위 세대의 객체를 포함하는 상위 세대의 참조를 추적하기 위한 card-table
; https://www.sysnet.pe.kr/2/0/1670

즉, 하위 세대의 객체(Bar)를 포함하는 상위 세대의 참조(Foo)를 추적하기 위해 card table이 존재하고, 이때 "foo.Bar = new Bar();"와 같이 대입이 될 때 card table을 업데이트하기 위한 "Write Barrier" 코드를 수행해야 하는 것입니다.

그런데 개인적으로 의문이 드는 것이 있다면, 보통 Barrier에 대해 write/read가 사용되면 CLR에 적용된 메모리 모델에 따른 용어(Memory Barrier)이고 이것은 CPU가 명령어 실행을 최적화하는 과정에 임의로 순서를 바꾸지 못하도록 하는 역할을 합니다. 따라서 JIT_WriteBarrierEAX보다는 JIT_UpdateCardTable이라는 용어가 더 적합했을 텐데 왜? WriteBarrier라는 용어를 굳이 사용했느냐입니다.

어쩌면 GC와의 연동에서 Memory barrier의 역할도 해야 하기 때문에 그런 걸 수도 있지만... 현재 제 수준으로는 딱히 단정 지을 수가 없군요. ^^

참고로, Brick 테이블은 interior pointer의 참조를 기록하는 용도이며 Card 테이블이 128(x86), 256(x64)의 크기로 유지되는 반면 Brick 테이블은 2kB(x86), 4kB(x64)라는 차이가 있습니다.

이와 관련해 좀 더 자세하게 알고 싶다면 다음의 책을 추천한다고.

Pro .NET Memory Management 
; https://prodotnetmemory.com/

(첨부 파일은 이 글의 예제 코드를 포함합니다.)



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







[최초 등록일: ]
[최종 수정일: 4/19/2024]

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

비밀번호

댓글 작성자
 




... 61  62  63  [64]  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12042정성태10/26/201911133오류 유형: 573. OneDrive 하위에 위치한 Documents, Desktop 폴더에 대한 권한 변경 시 "Unable to display current owner"
12041정성태10/23/201911140오류 유형: 572. mstest.exe - The load test results database could not be opened.
12040정성태10/23/201911382오류 유형: 571. Unhandled Exception: System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied
12039정성태10/22/20199811스크립트: 16. cmd.exe의 for 문에서는 ERRORLEVEL이 설정되지 않는 문제
12038정성태10/17/20199369오류 유형: 570. SQL Server 2019 RC1 - SQL Client Connectivity SDK 설치 오류
12037정성태10/15/201915297.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?파일 다운로드1
12036정성태10/14/201916326.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201912466개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201911824개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201915498개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201911983.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/20199403오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201915665.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201915776제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201911560.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/20198842오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201912502.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201910843제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201912284.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201912707.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201915756개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201927631도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201914486VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/20199831Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/20198824오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201911853오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
... 61  62  63  [64]  65  66  67  68  69  70  71  72  73  74  75  ...