This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Don't make the "getSum" method synchronized. Nothing much happens in it that would need to be synchronized anyway. To ensure that the value of the field "sum" is seen correctly between threads you should declare it volatile, though.
Neeraj jain wrote:I have a deadlock situation ..... Please tell me how should i remove it
Ulf's basically told you, but another thing to remember about synchronization is that it should be minimal. Your sum calculation goes through an enormous loop that holds onto a monitor for its entire execution, which is completely unnecessary. See if you can work out the difference with this:
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
And I think we shouldn't subclass Thread to create our threads unless
we need to provide a custom implementation of methods other than the run
method. Implementing Runnable should be the way to create threads for
all other cases.
To avoid deadlock, one of the rules-of-thumb is:
If a thread, during its flow, is acquiring locks L1 and L2 in a specific order, then all the threads should acquire the locks in the same order.
Currently, in OP's code, first thread locks r1 and then attempts to lock r2. However second thread does exactly opposite - this is classic scenario of deadlock.
Of course, suggestions by Ulf and Winston would work, and the rule mentioned above is not silver-bullet solution to fix deadlock issues, but following that rule has saved a lot of my time(and I could identify potential deadlocks before they actually occurred).
Anayonkar Shivalkar yes you are completely right but by using your way my program would be reached in an another world because basically i am trying to calculate personal sum in both diffrent threads diffrently then trying to get sum of another thread ... so for this problem your solution upto i think will not work . please correct me if i am wrong
Neeraj jain wrote:Anayonkar Shivalkar yes you are completely right but by using your way my program would be reached in an another world because basically i am trying to calculate personal sum in both diffrent threads diffrently then trying to get sum of another thread ... so for this problem your solution upto i think will not work . please correct me if i am wrong
Well, in that case, as mentioned, Ulf and Winston's suggestions would work.
Btw, I guess you need to do some extra coding to ensure the ordering (e.g. if first thread is calculating the sum, and what if second thread is not yet started, or finished calculating its own sum?)