For the following code
def stack(n: Int): Int = {
try stack(n+1)
catch {
case e: StackOverflowError => {
val inMB = 1024 * 1024
val totalMemory = Runtime.getRuntime().totalMemory() / inMB
val maxMemory = Runtime.getRuntime().maxMemory() / inMB
val freeMemory = Runtime.getRuntime().freeMemory() / inMB
println(n, totalMemory, maxMemory, freeMemory)
n
}
}
}
stack(0)
stack
function should get the max size of stack and print runtime memory usage infomation.
But the result is not as except.
For example
$ scala
Welcome to Scala 2.13.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181).
Type in expressions for evaluation. Or try :help.
scala> def stack(n: Int): Int = {
| try stack(n+1)
| catch {
| case e: StackOverflowError => {
| val inMB = 1024 * 1024
| val totalMemory = Runtime.getRuntime().totalMemory() / inMB
| val maxMemory = Runtime.getRuntime().maxMemory() / inMB
| val freeMemory = Runtime.getRuntime().freeMemory() / inMB
| println(n, totalMemory, maxMemory, freeMemory)
| n
| }
| }
| }
stack: (n: Int)Int
scala> stack(0)
(5845,94,228,52)
res0: Int = 5845
scala> stack(0)
(3673,94,228,43)(3672,94,228,43)(3671,94,228,43)(3670,94,228,43)
res1: Int = 3670
scala> stack(0)
(14695,94,228,33)(14694,94,228,33)(14693,94,228,32)(14692,94,228,32)(14691,94,228,32)(14690,94,228,32)(14689,94,228,32)(14688,94,228,32)(14687,94,228,32)(14686,94,228,32)(14685,94,228,32)(14684,94,228,32)(14683,94,228,32)(14682,94,228,32)(14681,94,228,32)(14680,94,228,32)(14679,94,228,32)
res2: Int = 14679
...
scala> stack(0)
(14701,115,228,44)(14700,115,228,44)(14699,115,228,44)(14698,115,228,44)(14697,115,228,44)(14696,115,228,44)(14695,115,228,44)(14694,115,228,44)(14693,115,228,44)(14692,115,228,44)(14691,115,228,44)
res36: Int = 14691
...
scala> stack(0)
(14701,108,228,54)(14700,108,228,54)(14699,108,228,54)(14698,108,228,54)(14697,108,228,54)(14696,108,228,54)(14695,108,228,54)(14694,108,228,54)(14693,108,228,54)(14692,108,228,54)(14691,108,228,54)(14690,108,228,54)(14689,108,228,54)
res84: Int = 14689
As the number of function calls increases, so does the result changes.
I have some questions here
- Why the first result of
stack(0)
output one line as except while call to function after print output result multiple times? - Why the stack size will change from 5748 down to 3670(It sems not happen every time), then increase as the function invokes much times?