Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads and synchronisation

 
Y Enev
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Y Enev
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In that case is there a way to achieve the result from the first case but using synchronised method?
 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic