Just before the main method exits, the account’s number field is guaranteed to have value 2000.
It says the value is false. When i change the code in main method like this
It prints out the value 2000. Here is what i understood the flow of the program
1- There are three threads, namely main, one and two.
2- Thread one and two both are acting on the same account object which means, any change in account object made by
thread is visible in account copy of the other thread.
3- In main method, we have made sure, main thread starts when thread one and thread two ends, it means it will only
print the print out statement once both of threads have finished. Both of the threads will also run the counter 1000 times.
Then why in case one, it doesn't guarantee the value 2000, but once i changed the code in main method, it makes sure.
I know i am sounding a bit weak here but please any help will be highly regarded.
Thread one and two will be runnable at the same time, while the Main thread blocks on thread one and thread two. This can cause the condition where both threads reach at the exact same time (racing condition). In this case, the account number will not be incremented by two (since two threads run), but by one. Since they both retrieve the exact same value and both use this exact same value to increment the account number by 1.
However, when you change the code to:
The main thread will block on one.join() until thread one is finished running, after which it starts the second thread, and blocks again. In this case, thread one and two won't be runnable at the same time. Preventing the racing condition with Hence the account number will be guaranteed to be incremented by one during each loop iteration in each thread.
Edit: Even though getNumber() and setNumber(Integer) are synchronized, the synchronization only applies to what is within the methods. The statement: consists of two separately executed statements: and
Joined: Mar 28, 2011
Welcome to Java-ranch. Thanks man. It was a great explanation. It really helped me clear the concept.
Thanks again for a great explanation
Joined: Mar 28, 2011
Here is sample Q-59 from Niko's Blog. Here is the sample code. The code is same except now it is not
getting anything, simply incrementing the value of integer by 1 and as the method is synchronized, it can
only be called by one thread at a time. So it means that this time order of joining threads doesn't matter
because one thread will block the other for sure.