• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Race condition trouble

 
Ray Hsia
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm about to go mad trying to debug this program


It's odd. Everytime I put a breakpoint at , the expected result, 1000, comes out.
However, whenever I just run the program, I keep getting a whole slew of random numbers.
I thought that if I put synchronized on my add function that it would stop the race condition, yet it still seems to be happening.
Any idea why it's still happening?
 
Wilhelm Vogt
Greenhorn
Posts: 10
Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ray,
some hint: you might want to read up the javadoc for Executor.execute() and note that setting a breakpoint at the position you indicated almost certainly changes the execution order of the threads.
Regards Wilhelm

edit: adding

at the end of the main method might also provide some insight
 
Henry Wong
author
Marshal
Pie
Posts: 21185
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ray Hsia wrote:
However, whenever I just run the program, I keep getting a whole slew of random numbers.
I thought that if I put synchronized on my add function that it would stop the race condition, yet it still seems to be happening.
Any idea why it's still happening?


First, synchronization is a tool. It is simply a mutually exclusive lock that can be used to solved race conditions. It is *not* a keyword, that when used, magically solves race conditions... You need to understand what the race conditions are, and how to solve it.

You have three race conditions in your application. One, when two or more threads try to change the value at the same time, it is not thread safe. Two, when you try to read the value in one thread, while another tries to change it, it is not thread safe. And three, you need to read the "final" result, in the main thread, after all the other threads are actually finished processing.

You solved the first race condition -- although I am not sure if you understand how you did it. You still have to solve the other two race conditions.

Henry
 
Thomas Krieger
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the corrected Version:



First, also synchronize the reads to avoid visibility problems, see for example java race conditions.
Second, wait till all threads ar finished using executor.isTerminated().
Third, only after all threads are finished get the result.


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic