Garbage Collection in Cache Manager
The cache manager CacheManager deletes unused caches at the first call from sequential code.
In addition, garbage collection runs automatically on exiting a parallel region.
The mathematical kernel provides an interface for clearing cached data – the MbGarbageCollection class.
The MbGarbageCollection class is the garbage collector which clears caches in registered objects of the CacheCleaner type. By request it deletes caches in the registered objects.
In order to enable garbage collection in an object of type CacheCleaner, the object needs to implement the ResetCacheData() method for caches cleaning and to subscribe to garbage collection in the MbGarbageCollection class.
The CacheManager class is derived from the CacheCleaner class, which makes it possible to run caches clearing in CacheManager automatically. For that, when creating a cache for a thread the cache manager registers itself in the MbGarbageCollection class.
Base Class for Objects that Require Garbage Collection
In order to subscribe to garbage collection, a class should be derived from the CacheCleaner class and should implement the ResetCacheData method for deleting cached data.
CacheCleaner is the base class for objects that require garbage collection. It implements the methods:
void SubcribeOnCleaning() – subscribe the object for garbage collection.
void UnsubcribeOnCleaning() – unsubscribe the object from garbage collection.
The CacheCleaner class also defines the method:
bool ResetCacheData() – reset cached data. Should return true if cached data was cleared and the object was unsubscribed from garbage collection.
Class MbGarbageCollection
The MbGarbageCollection class is the garbage collector for objects of type CacheCleaner, which keep cached data. By request MbGarbageCollection clears caches in registered objects by calling ResetCacheData for each object.
The MbGarbageCollection class implements the methods:
void Subscribe( CacheCleaner * obj ) – subscribe the object to garbage collection.
void Unsubscribe( CacheCleaner * obj ) – unsubscribe the object from garbage collection.
static bool Run( bool force = false ) – perform garbage collection. Should be called in sequential code. When called in a parallel region, does nothing. If force == false, then run garbage collection in caches created for threads which are finished; if force == true, then force garbage collection in all caches. Returns true if garbage collection is done.
static void Enable( bool allow = true ) – enable/disable collecting data for garbage collection. By default it is enabled.