0

I've got a question about mixing multithreading and recursive methods alltoghether. Let's say, you work with objects in your threads which have some recursive methods. Is there any chance for stackoverflow exceptions? To be frank, I've wrote a shop simulation, where i'm using only one recursive method for genereting unique id's and i'm reciving stackoverflow exception after about 1 minute. Have you ever had the same problems or I'm the first? :(

Thanks in advance :)

Matt_DontKnow
  • 39
  • 1
  • 7
  • 2
    It may not have to do with multithreading. Be more specific about where your code fails: did you begin to run the thread? What have you tried so far? – Heman Gandhi Feb 04 '16 at 01:36
  • Do you encounter a stackoverflow when running your shop simulation on a single thread? It would also be helpful to see the shop simulation code. – Jonny Henly Feb 04 '16 at 01:37
  • You are definitely not the first one. Look at this question: http://stackoverflow.com/questions/860550/stack-overflows-from-deep-recursion-in-java – nolexa Feb 04 '16 at 01:42
  • Problem has been solved. Thanks anyway. – Matt_DontKnow Feb 04 '16 at 01:55

2 Answers2

0

You Will get such Exception for 2 reasons. 1. Multithread or not, if your method has a risk of never ending calling itself you'll get a StackOverflowException but that would be a pure code error. 2. If your class is a Singleton with an attribute accessed by multiple threads you get a risk of the attribute modified by another thread causing current thread never to reach end of recursion because the attribute it uses is modified unexpectedly. If so maybe make that attribute Thread local. Maybe share some code so we can better help.

Damien Polegato
  • 508
  • 4
  • 13
  • Thanks a lot. I'm a bit tired, but i've found already what was causing a problems. Everything was about Random nextInt(param) method. – Matt_DontKnow Feb 04 '16 at 01:53
0

In addition to what others have already mentioned, you may be running out of stack space. You can set the stack size by setting the command line option -Xss. For example: java -Xss 1M MyClass

Be careful not to set it too high. If you keep setting it higher and keep getting a stack overflow, you probably have something wrong with your recursion as others have already pointed out.

csteel
  • 428
  • 1
  • 3
  • 14