It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronizing a block on an object. 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 "Synchronizing a block on an object." Watch "Synchronizing a block on an object." New topic
Author

Synchronizing a block on an object.

vijayakrishna Mikkilineni
Greenhorn

Joined: Nov 10, 2009
Posts: 24
If we synchronize a block of code (not method) on an object, does that mean only one thread can execute that block of code and manipulate the instance variables in that object? I want to know how synchronizing a block of code works.


Vijayakrishna M
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18520
    
  40

vijayakrishna Mikkilineni wrote:If we synchronize a block of code (not method) on an object, does that mean only one thread can execute that block of code and manipulate the instance variables in that object? I want to know how synchronizing a block of code works.


Only one thread can own the lock on an object at a time. So, if more than one thread wants to execute the same block of code, using the same synchronization object, only one can run at a time. Furthermore, if different blocks of code want to use the same synchronization object, then only once can run at a time, as well -- even for different blocks of code.

Henry


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

Joined: Mar 04, 2009
Posts: 417
Henry, it's not necessary to synchronize a method that does NOT manipulate instance variables, right?

Thank you!
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

Leandro Coutinho wrote:Henry, it's not necessary to synchronize a method that does NOT manipulate instance variables, right?

Yes its not necessary, but its done for thread safety...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
Ankit Garg wrote:Yes its not necessary, but its done for thread safety...

Why is it done for thread safety if local variables are not shared between threads? I didn't understand what you mean.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

Oops, I read what you wrote wrong, yes its not necessary to synchronize a method which don't manipulate/access instance variables...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronizing a block on an object.
 
Similar Threads
Blocks can be synchronized
locking with multiple objects
Exercise 9-2 K&B Page 710
Synchonized
To which of the following can we apply the synchronized keyword