When I tried to test the stack depth of the scala REPL, I found this probelm.
This is my code:
scala> def factorial(n : BigInt): BigInt = if (n == 0) 1 else n * factorial(n - 1)
factorial: (n: BigInt)BigInt
scala> factorial(10000)
java.lang.StackOverflowError
at scala.runtime.BoxesRunTime.equalsNumObject(BoxesRunTime.java:140)
at .factorial(<console>:13)
at .factorial(<console>:13)
...
Until now, the results are expected, but when I try to rerun(about 3 more times), it actually worked.
scala> factorial(10000)
res70: BigInt = 2846259680917054518906413212119868890148051401702799230794179994274411340003764443772990786757784775815884062142317528830042339940153518739052421161382716174819824199827592418289259787898124253120594659962598670656016157203603239792632873671705574197596209947972034615369811989709261127750048419884541047554464244213657330307670362882580354896746111709736957860367019107151273058728104115864056128116538532596842582599558468814643042558983664931705925171720427659740744613340005419405246230343686915405940406622782824837151203832217864462718382292389963899282722187970245938769380309462733229257055545969002787528224254434802112755901916942542902891690721909708369053987374745248337289952180236328274121704026808676921045155584056717255537201585213282903427998981844931361064038148...
Futher more, it show the following phenomenon
- that's alaways a number
n
, for functionfactorial(n)
, it will throw StackOverFlowError at the first time. - if you try this line more times, it will work sometimes.
- if you have tried enough times, it then become alaways work.
- however, if you redefine the function
factorial
, it will throw StackOverFlowError.
I guess this may cause by JVM or JIT, but I know few about those.
My question is : What causes this problem and how to explain this phenomenon ?
Test Environment
- Scala 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181)
- Scala 2.12.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_141)
Here is another similar question: scala-factorial-on-large-numbers-sometimes-crashes-and-sometimes-doesnt