Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpredictable Program Behaviour in Java

I'm pulling my hair out with this and I thought I'd see if the greater Java experience of others might be able to shed some light on the problem. There is a large amount of program code I have written, which is itself within a larger project so I can't simply post it. However, I will outline the problem...

The issue: My code does not return predicatble results from a simulation. Each time the simulation is run, various statistics are recorded. Despite the fact that the code is identical (!), the results produced differ between executions.

Things I am pretty sure are not a problem (although if you think there's a "gotcha" please shout out):

  • A random number generator is used but it is seeded with the same value each time.
  • The program is single threaded so race conditions should not be an issue.
  • Behaviour occurs in both debug mode, standalone jar and normal execution from the IDE (I'm using eclipse).
  • Static members are used between objects in lists. The for-each construct is used, but this should execute in the same order each time.
  • In the case of sorting the lists just mentioned, Collections.sort() is utilised and so should be stable (again, lists should be ordered in the same order)

Can anyone think of something I might be overlooking here? This seems unfathomable at the moment! Thanks!

like image 393
JavaDev12345 Avatar asked Jan 22 '23 12:01

JavaDev12345


2 Answers

Are you sure that you are using the instance of Random that you created in all places? Remember that calls to Math.random() use their own instance of Random.

like image 69
DJClayworth Avatar answered Feb 03 '23 07:02

DJClayworth


I'm assuming you've overridden both equals() and hashCode() in your objects (or you've written a custom comparator). If your random number is used in your objects, it's not a criteria in the sort, right?

Also, if you're sorting these items then placing them into a HashMap or a HashSet - these structures will not preserve your order - use TreeSet or TreeMap instead.

like image 27
Vinnie Avatar answered Feb 03 '23 07:02

Vinnie