This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronizing a block on an object.

 
vijayakrishna Mikkilineni
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 21405
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry, it's not necessary to synchronize a method that does NOT manipulate instance variables, right?

Thank you!
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, I read what you wrote wrong, yes its not necessary to synchronize a method which don't manipulate/access instance variables...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic