13

I'm coming from Java world, and there are plenty implementations of (local) in-memory caches. Moreover in Java world there are SoftReference and WeakReference, and they're, by definition, ideal for cache implementation(s).

I know that JavaScript does not have anything similar, so I'm wondering is it possible to have some sort of cache functionality which will delete/release (all) cached objects if there are "low memory pressure". So far, I know for lru-cache module, but it's implementation holds objects up to some number/size, which is nice, but not good enough because, naturally, you'd expect from cache to release objects if there are not enough memory.

Is it even possible to get some event in NodeJS from system when process is running low on memory?

Or maybe some library that could raise an event, something like:

var cmmm = require('cool_memory_management_module');

cmmm.on('low_memory', function(){
    //signaling to clear cache entries
});

So far, I've found npm memwatch, and npm usage modules, but still not able to combine all those pieces together.

Tomo
  • 6,847
  • 1
  • 22
  • 32
  • I found these: http://nodejs.org/api/process.html#process_process_memoryusage, http://nodejs.org/api/os.html#os_os_freemem. I don't have knowledge of how processes and memory relate to be able to tell if any of those functions is what you need. – Andreas Hultgren Jan 23 '14 at 14:38
  • 1
    thx @Andreas, I've seen this ones, but they're not enough for 'low memory event' implementation, and os.freemem() is useless within application process, since this is not memory you could use, only info about your environment... – Tomo Jan 23 '14 at 18:29

1 Answers1

5

There are no WeakReferences or similar in JS yet, but shall come in ES6 (Version List).

So far, now you could build something that just checks every few seconds if the memory is running out and clean up your map.

setInterval(function() {
    /* check if memory low and do something */
}, 2000).unref();
Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
CFrei
  • 3,552
  • 1
  • 15
  • 29
  • 1
    Ok, but that part *check if memory low* is interesting. how do you know if memory is low? process.memoryUsage() actually does not say anything like "you're low on memory". only current heapTotal and heap usage, but in the next moment, V8 could "malloc" more memory, so heapTotal would change.. – Tomo Jan 24 '14 at 10:29
  • 1
    Jep. If you really want to do it in very single roundtrip, click yourself into `process.nextTick()`. – CFrei Jan 24 '14 at 15:00