Skip to content

Instantly share code, notes, and snippets.

@fanf
Last active December 16, 2019 15:11
Show Gist options
  • Save fanf/74200e350a7d14fd1b0cf1f03406c2fd to your computer and use it in GitHub Desktop.
Save fanf/74200e350a7d14fd1b0cf1f03406c2fd to your computer and use it in GitHub Desktop.
package com.normation
import scala.concurrent.Future
object CheckMemoryReleaseFlatMap {
def getFreeMem = (Runtime.getRuntime().freeMemory() / (1024*1024)).toString + " MB"
def doGC = {
System.gc()
System.runFinalization()
}
// this array is 200MB
def newBigArray() = Array.fill(50 * 1024)(Array.fill(1024)("x"))
implicit val ec = scala.concurrent.ExecutionContext.global
/*
* Configuring jvm with -Xmx500M -Xms500M
*/
def test0(): Unit = {
Future {
doGC
println("t0: " + getFreeMem) // t0: 493 MB
doGC
for {
a <- Some(newBigArray())
_ = doGC
_ = println("t1: " + getFreeMem) // t1: 292 MB
_ = doGC
b <- Some(newBigArray())
_ = doGC
_ = println("t2: " + getFreeMem) // t2: 91 MB
_ = doGC
} yield {
doGC
Thread.sleep(2000)
println("t3: " + getFreeMem) // t3: 91 MB
Unit
}
}
Thread.sleep(5000)
doGC
println("t4: " + getFreeMem) // t4: 493 MB
}
def test1(): Unit = {
Future {
doGC
println("t0: " + getFreeMem) // t4: 493 MB
doGC
for {
x <- for {
a <- Some(newBigArray())
_ = doGC
_ = println("t1: " + getFreeMem) // t1: 292 MB
_ = doGC
b <- Some(newBigArray())
} yield b
_ = doGC
_ = println("t2: " + getFreeMem) // t2: 292 MB
_ = doGC
} yield {
doGC
Thread.sleep(2000)
println("t3: " + getFreeMem) // t3: 292 MB
Unit
}
}
Thread.sleep(5000)
doGC
println("t4: " + getFreeMem) // t4: 493 MB
}
def test2(): Unit = {
doGC
println("t0: " + getFreeMem) // t0: 493 MB
doGC
val a = Some(newBigArray())
doGC
println("t1: " + getFreeMem) // t1: 292 MB
doGC
val b = Some(newBigArray())
doGC
println("t2: " + getFreeMem) // t2: 91 MB
}
def test3(): Unit = {
doGC
println("t0: " + getFreeMem) // t0: 493 MB
doGC
{
val a = Some(newBigArray())
doGC
println("t1: " + getFreeMem) // t1: 292 MB
doGC
val b = Some(newBigArray())
doGC
println("t2: " + getFreeMem) // t2: 91 MB
}
doGC
println("t3: " + getFreeMem) // t3: 91 MB => ????
}
def main(args: Array[String]): Unit = {
println("======= test 0 ========")
test0
doGC
println("======= test 1 ========")
test1
doGC
println("======= test 2 ========")
test2
doGC
println("======= test 3 ========")
test3
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment