1

What mechanisms of the C# language are used in order to pass an instance of an object to the GC.AddMemoryPressure method?

I met the following code sample in the CLR via C# book:

private sealed class BigNativeResource {
    private readonly Int32 m_size;
    public BigNativeResource(Int32 size) {
        m_size = size;
        // Make the GC think the object is physically bigger
        if (m_size > 0) GC.AddMemoryPressure(m_size);
        Console.WriteLine("BigNativeResource create.");
    }
    ~BigNativeResource() {
        // Make the GC think the object released more memory
        if (m_size > 0) GC.RemoveMemoryPressure(m_size);
        Console.WriteLine("BigNativeResource destroy.");
    }
 }

I can not understand how do we associate an instance of an object with the pressure it adds. I do not see object reference being passed to the GC.AddMemoryPressure. Do we associate the added memory pressure (amp) with an object at all?

Also, I do not see any reasons in calling the GC.RemoveMemoryPressure(m_size);. Literally it should be of no use. Let me explain myself. There are two possibilities: there is an association between the object instance or there is no such association.

In the former case, the GC should now the m_size in order to prioritize and decide when to undertake a collection. So, it definitely should remove the memory pressure by itself (otherwise what would it mean for a GC to remove an object while taking into an account the amp?).

In the later case it is not clear what the use of the adding and removing the amp at all. The GC can only work with the roots which are by definitions instances of classes. I.e. GC only can collect the objects. So, in case there is no association between objects and the amp I see no way how the amp could affect the GC (so I assume there is an association).

1
  • The GC also needs to know how much memory is in use so it knows how urgent a collection is. If some of that memory is unmanaged, the GC doesn't see it. That's what those methods are for. Feb 26, 2020 at 20:00

3 Answers 3

7

I can not understand how do we associate an instance of an object with the pressure it adds.

The instance of the object associates the pressure it adds with a reference to itself by calling AddMemoryPressure. The object already has identity with itself! The code which adds and removes the pressure knows what this is.

I do not see object reference being passed to the GC.AddMemoryPressure.

Correct. There is not necessarily an association between added pressure and any object, and regardless of whether there is or not, the GC does not need to know that information to act appropriately.

Do we associate the added memory pressure (amp) with an object at all?

The GC does not. If your code does, that's the responsibility of your code.

Also, I do not see any reasons in calling the GC.RemoveMemoryPressure(m_size)

That's so that the GC knows that the additional pressure has gone away.

I see no way how the amp could affect the GC

It affects the GC by adding pressure!


I think there is a fundamental misunderstanding of what's going on here.

Adding memory pressure is just telling the GC that there are facts about memory allocation that you know, and that the GC does not know, but are relevant to the action of the GC. There is no requirement that the added memory pressure be associated with any instance of any object or tied to the lifetime of any object.

The code you've posted is a common pattern: an object has additional memory associated with each instance, and it adds a corresponding amount of pressure upon allocation of the additional memory and removes it upon deallocation of the additional memory. But there is no requirement that additional pressure be associated with a specific object or objects. If you added a bunch of unmanaged memory allocations in your static void Main() method, you might decide to add memory pressure corresponding to it, but there is no object associated with that additional pressure.

8
  • 1
    I got everything from the answer. Thank you. Could you, please, help with one more thing just to check my understanding. Could I wrote a piece of code that would actually add amp by using a few unmanaged resources which would take up memory, but instead of telling the GC about each resource separately just tell the GC about the aggregated amp? And later on get rid from all the objects and remove the aggregated amp respectively? In the end having only to instructions for the GC, but more than one managed object which led to the unmanaged memory allocation.
    – qqqqqqq
    Feb 26, 2020 at 20:30
  • @qqqqqq: Yes, that would be appropriate. The GC doesn't care if you call AMP(10); AMP(10); AMP(10); or AMP(30); Feb 26, 2020 at 20:31
  • 1
    @qqqqqqq: You are welcome! The .NET GC is a strange and wonderful creation with many interesting quirks. Fortunately, the vast majority of the time you do not need to understand how it works. But it is fascinating to learn about it. Feb 26, 2020 at 20:32
  • @qqqqqqq: A good exercise is: suppose that the GC did track additional memory pressure per object. This would mean, as you note, that there would be no need to relieve additional memory pressure because the GC could do so when the associated object is collected. Think about how you might implement that feature. The GC isn't magic; it's written by people, and those people have to write code in a programming language like all of us. There are a lot of ways to implement that feature, and they all add costs; what are those costs? Feb 26, 2020 at 20:43
  • I believe we could just store the Int64 value passed to the AddMemoryPressure in an associated with an object "field". And make the GC know about the field. The costs are the time for the GC to include the field in its computations (which I believe happen anyway) and the 8-byte of memory for each such field.
    – qqqqqqq
    Feb 26, 2020 at 21:00
2

These methods exist to let GC know about memory usage outside of managed heap. There is no object to pass to these methods because memory is not directly related to any particular managed object. It's responsibility of author of the code to notify GC about change in memory usage correctly.

GC.AddMemoryPressure(Int64)

… the runtime takes into account only the managed memory, and thus underestimates the urgency of scheduling garbage collection.

Extreme example would be you have 32 bit app and GC thinks it can easily allocate almost 2GB of managed (C#) objects. As part of the code you use native interop to allocate 1GB. Without the AddMemoryPressure call GC will still think it's free to wait till you allocate/deallocate a lot of managed objects... but around the time you allocated 1GB of managed objects GC runs into strange state - it should have whole extra GB to play with but there is nothing left so it has to scramble to collect memory at that point. If AddMemoryPressure was properly used GC would had chance to adjust and more aggressively collect earlier in background or at points that allowed shorter/smaller impact.

5
  • Does that mean that GC analyzes the whole memory taken (including the unmanaged memory as specified by the amp) and then randomly collects objects until it sees that enough memory is gone (meaning the extra amp is gone)?
    – qqqqqqq
    Feb 26, 2020 at 20:20
  • 1
    @qqqqqqq: The notion that the GC does random collections is a strange one. The GC collection regimen is heuristic but it is not typically thought of as random. Feb 26, 2020 at 20:26
  • 2
    @qqqqqqq: The GC knows facts about the amount of managed memory that is allocated, the amount of virtual address space that is available, the amount of physical memory that is available, and so on. We summarize this information as pressure; that is, how hard are we pushing on the boundaries of available memory? When sufficient pressure is reached and we believe that collection would relieve pressure, a collection of the appropriate generation is triggered. Feb 26, 2020 at 20:28
  • @EricLippert, does that mean that too much amp (which happened due to the calls to AddMemoryPressure) may force the GC to run collections before a generation budget is reached? Does the added in such a way (AddMemoryPressure) memory pressure may produce a lot of different GC behavior deviations, not only before budget collections?
    – qqqqqqq
    Feb 26, 2020 at 20:36
  • 2
    @qqqqqqq: If AddMemoryPressure is misused -- in particular, if one forgets to remove pressure when the unmanaged resource is released -- then yes, a likely effect is that the GC will do more collections sooner than it really ought to. As for whether there are additional knock-on effects, there I do not know enough about the GC details to say for sure. Feb 26, 2020 at 20:41
2

AddMemoryPressure is used to declare (emphasis here) that you have sensible sized unmanaged data allocated somewhere. This method is a courtesy that the runtime gives to you.

The purpose of the method is to declare under your own responsibility that somewhere you have unmanaged data that is logically bound to some managed object instance. The garbage collector has a simple counter and tracks your request by simply adding the amount you specify to the counter.

The documentation is is clear about that: when the unmanaged memory goes away, you must tell the garbage collector that it has gone away.

You need to use this method to inform the garbage collector that the unmanaged memory is there but could be freed if the associated object is disposed. Then, the garbage collector is able to schedule better its collection tasks.

4
  • How can I associate a memory with an object? Should I just call the GC.AddMemoryPressure inside a constructor? I mean I never met such mechanisms. Is it a special function call that somehow implicitly passes an object reference to the AddMemoryPressure?
    – qqqqqqq
    Feb 26, 2020 at 20:17
  • 2
    There is no association per se. Keep in mind that the usage of this method is truly a niche. The association is a logical concept, while the gc is happy to know that somewhere it is there. It does not care why is there, nor who created it, but simply the existence. In your code, if you allocate an unmanaged array and really want to use this method, will simply call it in the constructor with the size on byte of the array. Likewise, in the finalizer of the object, you must revert the action. It is up to you to keep everuthing consistent. Is its little bit clearer?
    – Yennefer
    Feb 26, 2020 at 20:24
  • Yes, it is a lot more clear now. Thank you a lot. (y)
    – qqqqqqq
    Feb 26, 2020 at 20:39
  • You are welcome. As always, have a look at Eric's answer, which is much more detailed and precise.
    – Yennefer
    Feb 26, 2020 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.