Exception in thread "Thread-8" java.lang.StackOverflowError
at sun.misc.Unsafe.compareAndSwapLong(Native Method)
at java.util.concurrent.atomic.AtomicLong.compareAndSet(Unknown Source)
at java.util.Random.next(Unknown Source)
at java.util.Random.nextInt(Unknown Source)
at sim.ant.colony.ants.Forager.moveTo(Forager.java:108)
I’m working with a multi threaded application(Ant Simulation Colony) where I created every ant as a thread and when tens of threads (ants) are running, above exception occurs after every few turns and thread is killed. code where I’m using Random() is;
Random rand = new Random();
return adjacents.elementAt(rand.nextInt(8));
this code is written in a thread’s local member function. So assuming every thread creates random numbers hundred of times and there are more than ten threads are working.
Can somebody help me with this exception?
Not really an answer to your problem but more an example of the problem you have, how you can track it and how you can fix it.
Take the code below:
It will produce a StackOverFlowError instantly:
The problem is not in HashMap, nor HashMap$Entry. The problem is that a() and b() call each other recursively without a proper stop-condition, meaning infinitely. If you actually look below in the stack, you immediately discover that pattern:
You need to find the recursion that goes too deep in your code. Either fix it or change it to a non-recursive method.
Using a debugger can be of great help for that as you can step into each method call and put breakpoints (amongst plenty of other good stuffs).