• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

why does synchronized not work here?

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I'm just starting with threads, using Head First Java. I tried to code the Ryan and Monica example (Ryan and Monica both withdraw $10 at a time from their joint bank account...) and everything went swimmingly until I tried to put in a synchronized block to avoid overdrafts. If this works correctly, the total amount withdrawn should always be $100 (which is also true if I put the Thread.sleep() in a more reasonable location, but I'm doing this to figure out how threads work). However, in the code below, $110 gets withdrawn about 20% of the time on my machine.

What am I doing wrong?

Thank you!! Karen.

 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your two threads are synchronising on different objects, so the synchronisation has no effect. For it to work, they need to synchronise on the same object. Perhaps the outer class could create an object on which both inner classes can synchronise.
 
Karen Nelson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Wow, thank you! that's totally clear but I never would have figured it out... I made an Account object and synchronized on that and everything's fine.

-K
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic