wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes Race condition trouble Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Race condition trouble" Watch "Race condition trouble" New topic
Author

Race condition trouble

Ray Hsia
Greenhorn

Joined: Nov 08, 2013
Posts: 1
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

Joined: Jul 11, 2012
Posts: 9

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
Sheriff

Joined: Sep 28, 2004
Posts: 18520
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Thomas Krieger
Greenhorn

Joined: Oct 28, 2013
Posts: 2
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.


 
 
subject: Race condition trouble
 
Similar Threads
Please critic, rate or give some helpful advice
StringTokenizer(read from text File) help needed
collection classes
Executors in Threads
How to avoid race conditions?