Search code examples
javascriptnode.jsmemory-managementv8

NodejS: memory usage of worker threads


Is there a way to obtain heap usage statistics of each worker threads in nodejs? I'm looking for something similar to getHeapStatistics() of v8 module. Mostly i'll just be needing the values of used heap size and max heap limit.


Solution

  • As per Marc's comment, getHeapStatistics works in the worker threads. See example below:

    const { Worker, isMainThread, parentPort } = require("worker_threads");
    const { getHeapStatistics } = require("v8");
    
    if (isMainThread) {
      const worker = new Worker(__filename);
      worker.on("message", (msg) => {
        const heapSize = getHeapStatistics().total_heap_size;
        console.log(
          `In the main thread got message "${msg}", heap size is ${heapSize}`
        );
      });
      worker.on("error", (err) => {
        console.log(err);
      });
    } else {
      const bigArray = [];
      const heapSizeBefore = getHeapStatistics().total_heap_size;
      console.log(`In the worker thread, heap size is ${heapSizeBefore}`);
    
      parentPort.postMessage(`Array size ${bigArray.length}`);
    
      // Eat a lot of memory
      for (let i = 0; i < 100000000; i++) {
        bigArray.push(i);
      }
    
      const heapSizeAfter = getHeapStatistics().total_heap_size;
      console.log(`In the worker thread, heap size is ${heapSizeAfter}`);
      parentPort.postMessage(`Array size ${bigArray.length}`);
    }
    

    Gives output:

    11:21:22:~  $ node threads-example.js
    In the worker thread, heap size is 8019968
    In the main thread got message "Array size 0", heap size is 5922816
    In the main thread got message "Array size 100000000", heap size is 6193152
    In the worker thread, heap size is 2391023616
    11:21:44:~  $