File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads and synchronisation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads and synchronisation" Watch "Threads and synchronisation" New topic
Author

Threads and synchronisation

Y Enev
Greenhorn

Joined: Oct 14, 2006
Posts: 8
Hi,
While studying for the exam I'm trying some examples. This one made me wonder. The variant that synchronises a block works fine, but the one that synchronises a method doesn't. I'd appreciate if someone can shed some light on this puzzle.
Thanks.



[HENRY: Added code tags]
[ October 14, 2006: Message edited by: Henry Wong ]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18760
    
  40

While studying for the exam I'm trying some examples. This one made me wonder. The variant that synchronises a block works fine, but the one that synchronises a method doesn't. I'd appreciate if someone can shed some light on this puzzle.


In both your examples, you have three thread (testsync) objects holding a reference to the same string buffer object.

In the first case, the three threads are synchronizing on the same (string buffer) object, so hence, they will block while another is holding the lock.

In the second case, the three threads are synchronizing on the "this" object. Unfortunately, the three threads are using different TestSync objects, so have different "this" objects, and hence, they will never contend for a lock.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Y Enev
Greenhorn

Joined: Oct 14, 2006
Posts: 8
In that case is there a way to achieve the result from the first case but using synchronised method?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18760
    
  40

Originally posted by Y Enev:
In that case is there a way to achieve the result from the first case but using synchronised method?


To use the synchronize method technique for this example, you must be calling the synchronized method on the *same* object. You must create a new object, with the synchronized method, that can be shared by the three threads.

Henry
Y Enev
Greenhorn

Joined: Oct 14, 2006
Posts: 8
Thanks.
 
 
subject: Threads and synchronisation