my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronized - K&B sample Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronized - K&B sample" Watch "synchronized - K&B sample" New topic
Author

synchronized - K&B sample

Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
I modified money withDrawal illustration in K&B book by putting makeWithDrawal() method in another class called AccountTrans.

But I got different behaviour/output, until I put that line which called makeWithDrawal() in synchronized(this) block.

anyone can explain why I need to synchronized on "this" object and
synchronized on "public void makeWithDrawal" doesn't work anymore?

hope make sense




SCJP 5
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

The reason synchronizing makeWithdraw() doesn't work is because you are instantiating a new AccountTrans object for each call. As for why "this" works is unclear -- you didn't show enough of the code.

The main takeaway is this... In order to have threads be single threaded during thread unsafe areas of code, they must all synchronized with the same object.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
Thanks Henry.

I am trying to mimic real scenario where 2 people access one account, that's why I create 2 instances of AccountTrans.

maybe it is not a good design (I'm trying to apply pojo). please advise.

below is a missing class (from my first post). Account class only contains set and get methods.

Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

The reason using the "this" object works is because every thread uses the *same* object. Both of your threads uses a same runnable. And in you run() method, the "this" refers to the runnable object.

Henry
Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
Originally posted by Henry Wong:
Both of your threads uses a same runnable. And in you run() method, the "this" refers to the runnable object.
Henry


I know there are 2 AccountTrans instance, But... I pass them the same Account instance.

If I want to remove "synchronized(this)" block, could you advise me how should I refactor them?

thanks again
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronized - K&B sample
 
Similar Threads
Java Threads 2nd edition: ATM locking example does not synchronize. WHY?
synchronized - K&B sample
Regarding Syncronization
Synchronised Vs. Non synchronised Thread
Thread question