How to show memory usage in a running Scala application

You can show used, free, total, and max memory (RAM) available in a Scala application just like you do in Java. The lines of code look like this:

// memory info
val mb = 1024*1024
val runtime = Runtime.getRuntime
logger.log("** Used Memory:  " + (runtime.totalMemory - runtime.freeMemory) / mb)
logger.log("** Free Memory:  " + runtime.freeMemory / mb)
logger.log("** Total Memory: " + runtime.totalMemory / mb)
logger.log("** Max Memory:   " + runtime.maxMemory / mb)

That code will print the used, free, total, and maximum available memory in MB.

Here’s the same code with println instead of logger.log:

// memory info
val mb = 1024*1024
val runtime = Runtime.getRuntime
println("** Used Memory:  " + (runtime.totalMemory - runtime.freeMemory) / mb)
println("** Free Memory:  " + runtime.freeMemory / mb)
println("** Total Memory: " + runtime.totalMemory / mb)
println("** Max Memory:   " + runtime.maxMemory / mb)

This code is a Scala version of the Java code at this page on viralpatel.net.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.