0

Until now, I thought that the following construction would work with the GC:

    public class SampleClass
    {
        #region Statics
        public static int CacheCapacity
        {
            get => CacheCapacity_;
            set
            {
                int val = value < 0 ? 0 : value;
                if(ActiveSamples_ != null)
                {
                    if(val == 0)
                    {
                        ClearCache();
                        CacheCapacity_ = 0;
                        return;
                    }
                    if (val < ActiveSamples_.Count)
                    {
                        ShrinkCacheTo((int)(0.8D * val));
                    }
                }
                
                CacheCapacity_ = val;
            }
        }
        static int CacheCapacity_;
        protected static List<SampleClass> ActiveSamples
        {
            get
            {
                if(ActiveSamples_ == null)
                    ActiveSamples_ = new List<SampleClass>();
                return ActiveSamples;
            }
        }
        protected static List<SampleClass> ActiveSamples_;

        public static bool AddToCache(SampleClass instance)
        {
            if(CacheCapacity == 0)
                return false;
            if (ActiveSamples.Count >= CacheCapacity)
                ShrinkCacheTo((int)(0.8D * CacheCapacity));
            ActiveSamples.Add(instance);
            return true;
        }

        public static void ClearCache()
        {
            ActiveSamples_ = null;
        }

        protected static void ShrinkCacheTo(int size)
        {
            if (ActiveSamples_ == null)
                return;
            if (ActiveSamples_.Count <= size)
                return;
            List<SampleClass> tmp = new List<SampleClass>(size);
            for (int i = ActiveSamples_.Count-size; i < ActiveSamples_.Count; i++)
            {
                tmp.Add(ActiveSamples_[i]);
            }
            ActiveSamples_ = tmp;
        }
        #endregion

        #region Constructors and Instance getters

        public SampleClass(string instanceID)
        {
            InstanceID = instanceID;
            // time-consuming initialisation ...
            AddToCache(this);
        }
        public static SampleClass GetOrCreateInstance(string instanceID)
        {
            var result = ActiveSamples.Find(x => x?.InstanceID == instanceID);
            if (result == null)
                result = new SampleClass(instanceID);
            return result;
        }
        #endregion

        #region Instance members
        public string InstanceID { get; protected set; }
        public bool IsCached => ActiveSamples.Find(x => x?.InstanceID == InstanceID) == this;
        #endregion

    }

I allow to cache instances of SampleClass (that takes quite long to initialise) up to a certain capacity so that I do not always create them when I reference them again.

As ActiveSamples_ is static, the cached instances will not be collected by the GC, which is intended as long as they are referenced by ActiveSamples_. I supposed that they become garbage as soon as I assign null or a new List not containing them to ActiveSamples_ in ClearCache(), ShrinkCacheTo() (and, of course, if there are no further references to them).

Now my colleage who is hunting memory leaks read here (point 3 and 5) that my caching may raise the problem that, if the instances were once referenced by a static object, they will never become managed code afterwards. The code samples in the link do not provide any code that cuts the reference between the static List or Dictionary and its contents, so that it may only say that they will remain as long as they are referenced but the text can be understood in the way that the become and remain unmanaged.

My question is, what is correct:

  1. Former members of a static field are permanently out of the scope of the GC; they have to be disposed.
  2. Once the reference from the static field to the object is no more valid, the GC will automatically dispose them when it decides to do so.

If 1. is true how do I dispose them?

7
  • 1
    What do you mean with "Former members of a static field"? The static field is itself a member, it's value or former values are not members. Regardless of some instance being once held by a static field or some instance field, or some local variable, the only thing that matters to the GC is whether something still holds onto a reference of this instance or not. The GC does not care about past affairs of instances with static fields (it would be funny if it were, though...)
    – user19858830
    Sep 15, 2022 at 12:38
  • I mean the instances that once were items in ActiveSamples_ but are no more items of ActiveSamples_ because the reference from the static field to the list has been cut.
    – SDG
    Sep 15, 2022 at 12:44
  • @MySkullCaveIsADarkPlace I had also understood it as you say (2. is true), but I got puzzled cause my collegue told me to remove and avoid all static fields because he supposes that 1. is true. If you are sure that you are right, you can put it as an answer, so that I can accept it.
    – SDG
    Sep 15, 2022 at 12:50
  • 1
    (1/2) All that matters to the garbage collector is whether something in your program still holds a reference to an instance to decide whether that instance is collectable or not. If only the ActiveSamples_ list ever holds a reference to some instance, as soon as that instance is removed from the list (without anything else coming in and holding a reference to this instance) or when the list itself is unassigned (without anything else holding a reference of it), then the list will be subject to GC.
    – user19858830
    Sep 15, 2022 at 12:51
  • 1
    So, basically the answer to (1) is "Incorrect". And for (2) it all depends on what precisely you mean with "relation" (remember the caveats i did put in parantheses in my former comments?)
    – user19858830
    Sep 15, 2022 at 12:56

1 Answer 1

0

Résumé from the comments of MySkullCaveIsADarkPlace:

Answer to (1) is "Incorrect".

The GC does not care about past affairs of instances with static fields.

If only the ActiveSamples_ list ever held a reference to some instance, as soon as that instance is removed from the list (without anything else coming in and holding a reference to this instance) or when the list itself is unassigned (without anything else holding a reference of it), then the list will be subject to GC.

Answer 2 is correct, provided that there is nothing else in your program holding to those instances.

1
  • 2
    You can generalize this statement: the garbage collector doesn’t care about the past at all.
    – Holger
    Sep 20, 2022 at 7:01

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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