Resource Cache and Reference Counting
Ten goblins share one goblin mesh, one texture and one footstep sound. Loading those files ten times wastes memory and load time; freeing the mesh when the first goblin dies crashes the other nine. A resource cache (also called a resource manager or asset registry) solves both: it loads each asset once, hands out references to it, and keeps it alive exactly as long as something uses it.
| Responsibility | How |
|---|---|
| Load once | map from asset ID (path or hashed name) to the loaded object |
| Share | hand out handles or reference-counted pointers |
| Free when unused | count references; unload at zero, or keep for a while in case it is needed again |
| Stay within budget | evict unused assets when memory runs low |
| Reload | swap in a new version without breaking holders: see Hot Reload |
Asset IDs are usually hashed strings, as in String Interning and IDs, so lookups compare integers instead of paths.
Reference counting by hand
The cache below keeps an entry per asset with a count. acquire loads on first use and increments; release decrements and unloads at zero. A small RAII wrapper (TextureRef) does the counting automatically, the same idea as std::shared_ptr but with the count owned by the cache. If RAII is new, read RAII, Ownership and Lifetimes first.
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
struct Texture { std::string path; int width, height; };
class TextureCache {
public:
Texture* acquire(const std::string& path) {
Entry& e = entries_[path];
if (e.refs == 0 && !e.texture) {
e.texture = new Texture{path, 256, 256}; // stand-in for decoding a file
loads_++;
std::cout << " load " << path << "\n";
}
e.refs++;
return e.texture;
}
void release(const std::string& path) {
Entry& e = entries_.at(path);
if (--e.refs == 0) {
std::cout << " unload " << path << "\n";
delete e.texture;
entries_.erase(path);
}
}
int refs(const std::string& path) const { auto it = entries_.find(path); return it == entries_.end() ? 0 : it->second.refs; }
int loads() const { return loads_; }
private:
struct Entry { Texture* texture = nullptr; int refs = 0; };
std::unordered_map<std::string, Entry> entries_;
int loads_ = 0;
};
// RAII reference: copy = +1, destroy = -1.
class TextureRef {
public:
TextureRef(TextureCache& c, std::string path) : cache_(&c), path_(std::move(path)), tex_(c.acquire(path_)) {}
TextureRef(const TextureRef& o) : cache_(o.cache_), path_(o.path_), tex_(cache_->acquire(path_)) {}
TextureRef& operator=(const TextureRef&) = delete;
~TextureRef() { cache_->release(path_); }
const Texture* operator->() const { return tex_; }
private:
TextureCache* cache_;
std::string path_;
Texture* tex_;
};
int main() {
TextureCache cache;
std::cout << "spawn goblins\n";
{
TextureRef g1(cache, "goblin.png");
TextureRef g2(cache, "goblin.png");
TextureRef g3 = g2; // copy shares the same texture
TextureRef sky(cache, "sky.png");
std::cout << " goblin refs: " << cache.refs("goblin.png") << ", size " << g1->width << "x" << g1->height << "\n";
std::cout << "leave scope\n";
}
std::cout << "loads: " << cache.loads() << ", goblin refs now: " << cache.refs("goblin.png") << "\n";
}spawn goblins
load goblin.png
load sky.png
goblin refs: 3, size 256x256
leave scope
unload sky.png
unload goblin.png
loads: 2, goblin refs now: 0
Three goblins, one goblin texture load. When the last reference goes out of scope, the texture is freed.
Note: You could store
std::shared_ptr<Texture>in game objects andstd::weak_ptr<Texture>in the cache, and get the same behaviour from the standard library. Many engines don't, for three reasons: the atomic count in every copy costs a little on hot paths,shared_ptrmakes it hard to replace an asset in place for hot reload, and "freed the moment the count hits zero" is often not what you want (next section). Both designs are valid; pick one and use it everywhere.
Don't unload at zero: deferred eviction
Unloading the instant the count reaches zero causes thrashing: the last goblin dies, its mesh unloads, a new goblin spawns a second later and the mesh loads again. Most engines instead move zero-reference assets to an eviction list and only free them when memory is needed, oldest first (least recently used).
#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <unordered_map>
class AssetCache {
public:
explicit AssetCache(int budgetKb) : budget_(budgetKb) {}
void acquire(const std::string& id, int sizeKb) {
auto it = assets_.find(id);
if (it == assets_.end()) {
makeRoom(sizeKb);
assets_[id] = {sizeKb, 1, unused_.end()};
used_ += sizeKb;
std::cout << "load " << id << " (" << sizeKb << " KB), used " << used_ << " KB\n";
return;
}
Asset& a = it->second;
if (a.refs == 0) { unused_.erase(a.lru); std::cout << "revive " << id << " from the eviction list\n"; }
a.refs++;
}
void release(const std::string& id) {
Asset& a = assets_.at(id);
if (--a.refs == 0) { unused_.push_back(id); a.lru = std::prev(unused_.end()); }
}
private:
struct Asset { int sizeKb; int refs; std::list<std::string>::iterator lru; };
void makeRoom(int needKb) {
while (used_ + needKb > budget_ && !unused_.empty()) {
std::string victim = unused_.front(); // least recently released
unused_.pop_front();
used_ -= assets_[victim].sizeKb;
assets_.erase(victim);
std::cout << "evict " << victim << ", used " << used_ << " KB\n";
}
if (used_ + needKb > budget_) std::cout << "warning: over budget, everything is in use\n";
}
int budget_, used_ = 0;
std::unordered_map<std::string, Asset> assets_;
std::list<std::string> unused_; // zero-ref assets, oldest first
};
int main() {
AssetCache cache(1000);
cache.acquire("goblin_mesh", 300);
cache.acquire("goblin_tex", 400);
cache.release("goblin_mesh");
cache.release("goblin_tex"); // both idle but still loaded
cache.acquire("goblin_mesh", 300); // a new goblin: no disk access
cache.acquire("castle_tex", 500); // needs room: evicts the idle goblin_tex
cache.acquire("dragon_mesh", 600); // nothing idle left to evict
}load goblin_mesh (300 KB), used 300 KB
load goblin_tex (400 KB), used 700 KB
revive goblin_mesh from the eviction list
evict goblin_tex, used 300 KB
load castle_tex (500 KB), used 800 KB
warning: over budget, everything is in use
load dragon_mesh (600 KB), used 1400 KB
The second goblin came back from memory for free, and the eviction only happened when a new asset actually needed the space.
Design checklist
- IDs, not paths, at runtime. Hash paths at build time; ship a table for debugging.
- Asynchronous loads. A real
acquirereturns immediately with a handle in a loading state; the file is read and decoded on a job or I/O thread. Gameplay checksisReady()or draws a placeholder. - Dependencies. A material references textures and a shader. Loading the material acquires them; unloading releases them.
- Typed caches. One cache per asset type (meshes, textures, sounds) keeps budgets and loaders separate.
- Leak report at shutdown. Print every asset whose count is not zero when the level unloads. A non-zero count means some system forgot to release it.
Test yourself
What problem does deferred eviction (keeping zero-reference assets loaded) solve?
- Memory leaks
- Thrashing: unloading and reloading an asset that is needed again moments later
- Data races in the cache
- Hash collisions
In the LRU cache, which asset is evicted first when room is needed?
- The largest asset
- The asset with the most references
- The idle asset that was released longest ago
- The newest asset
What should a resource cache report when a level unloads?
- Nothing
- Assets whose reference count is still above zero, since they indicate leaks
- The total number of loads ever
- The file paths of all assets on disk