java - StackOverflowError in Math.Random in a randomly recursive method -
this context of program.
a function has 50% chance nothing, 50% call twice. probability program finish?
i wrote piece of code, , works great apparently. answer may not obvious program has 100% chance finish. there stackoverflowerror (how convenient ;) ) when run program, occuring in math.random(). point me come from, , tell me if maybe code wrong?
static int bestdepth =0; static int numberofprograms =0; @test public void testproba(){ for(int = 0; <1000; i++){ long time = system.currenttimemillis(); bestdepth = 0; numberofprograms = 0; loop(0); logger.info("best depth:"+ bestdepth +" in "+(system.currenttimemillis()-time)+"ms"); } } public boolean loop(int depth){ numberofprograms++; if(depth> bestdepth){ bestdepth = depth; } if(proba()){ return true; } else{ return loop(depth + 1) && loop(depth + 1); } } public boolean proba(){ return math.random()>0.5; } .
java.lang.stackoverflowerror @ java.util.random.nextdouble(random.java:394) @ java.lang.math.random(math.java:695) . suspect stack , amount of function in limited, don't see problem here.
any advice or clue welcome.
fabien
edit: answers, ran java -xss4m , worked great.
whenever function called or non-static variable created, stack used place , reserve space it.
now, seems recursively calling loop function. places arguments in stack, along code segment , return address. means lot of information being placed on stack.
however, stack limited. cpu has built-in mechanics protect against issues data pushed stack, , override code (as stack grows down). called general protection fault. when general protection fault happens, os notifies running task. thus, originating stackoverflow.
this seems happening in math.random().
in order handle problem, suggest increase stack size using -xss option of java.
Comments
Post a Comment