In Java, a weak reference is garbage collected if memory out. In Linux, malloc() always returns a strong reference, ie. the pointer is never freed until the caller call free() function.
I want to allocate a buffer for caching, which could be freed automatically when the memory is running out, like following:
cache_t cache;
if (! cache_alloc(&cache))
die("Memory out");
cache_lock(&cache); // realloc cache mem if it is collected
if (! cache->user_init) { // The "user_init" maybe reset if the cache mem is collected
// lazy-init the cache...
load_contents(cache->mem, ...);
cache->user_init = 1;
}
// do with cache..
stuff_t *stuff = (stuff_t *) cache->mem;
...
cache_unlock(&cache);
It seems the buff and cache in the output of vmstat is disk IO related:
$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 51604 554220 13384 314852 3 10 411 420 702 1063 8 3 75 14
Well, I want to know more about whether the cache in my example could be reflected in the “cache” column in the vmstat output.
There really isn’t a good way of doing it – the C memory model simply doesn’t allow for the same kind of behavior that the Java memory model allows. Java’s memory model of course builds on the C model when interfacing with the operating system, which is why the Java heap must be manually limited by the application launcher.
The “buff” and “cache” columns relate to the page/disk cache and internal buffers used by the kernel. These caches are automatically handled by the kernel – for instance, reading a file will place the contents in the “cache” usage number, in the same way that running out of memory will commit it to a swap device (“swpd”).