I need to have a large list of data that when referenced at a specific location calculates (loads from a file, and/or generates it if it hasn’t been generated yet) and keeps it for future use. This is powered by lazy lists bound to a function. These “chunks” sometimes are loaded but never really used after that while still effectively referenced in code so the GC doesn’t pick up on them.
Since the RAM quickly fills up, I’d like to lazily unload these chunks after a period of time where they aren’t used by anything. Is this possible?
You can implement this by using
unsafeInterleaveIOto read the chunks and periodically going through the list and removing the references to chunks that were not used for a long time (alternatively: use weak pointers as @nponeccop suggests in the comments), but I’d go with something that doesn’t rely on GC for managing memory for the chunks (since predictable memory usage is important for you).For example:
where
getChunkallocates the memory for missing chunks withmallocandfreeUnusedChunksgoes through the table andfrees unused chunks.You can even run
freeUnusedChunksin a separate thread: