This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Meteor in Action and have Stephan Hochhaus & Manuel Schoebel on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Problem in using Synchronized keyword correctly. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Meteor in Action this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem in using Synchronized keyword correctly." Watch "Problem in using Synchronized keyword correctly." New topic

Problem in using Synchronized keyword correctly.

Rohan Deshmkh
Ranch Hand

Joined: Aug 31, 2012
Posts: 127
I am trying to understand the synchronized keyword practically.So,Here's the problem:

Initial balance is 1000.It's a joint account of Robert and Kristen.
Both want to withdraw 1000 from that account at same time from different locations.
Now , here is the flow of program that i want to achieve:

Robert checks balance,see's it's enough
Robert sleeps
Krsiten checks balance, see it's enough
Krsiten withdraws
Now, when Robert wants to withdraw he see's that there no enough balance, so he get's a message "not enough balance"

Kristen and RObert names can be interchanged as we are not sure which one will be picked by jvm to execute first.

Here is my code:

Rohan Deshmkh
Ranch Hand

Joined: Aug 31, 2012
Posts: 127
I forgot to mention my problem.
I am getting output correctly, but from the above problem what i have achieved is:

Robert checks for balance,see's it's enough
Robert completes withdraw
Kristen checks for enough balance, it's not enough,so she gets a message " cannot withdraw due to Low balance"

I think that although i am getting the output correctly, this is not the correct approach to show the use of synchronized method.I think both should have checked if there's enough balance , for for both it should have told "yes there's enough balance".And then one of them should go for sleep,the other completes the withdrawal and when the second one when withdrawing should get the message "there's not enough balance"
Wesleigh Pieters
Ranch Hand

Joined: Sep 04, 2012
Posts: 81
the whole point of synchronizing the method is so that it can't possibly happen. if you don't synchronize it it could possibly do what you say, but remember there is no guarantee
I agree. Here's the link:
subject: Problem in using Synchronized keyword correctly.