• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is my Understanding Correct ?

 
Sid Robin
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This para is taken from K & B

"When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object´┐Żs lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock for code synchronization within a single object."

class SyncTest {
public void doStuff() {
System.out.println("not synchronized");
synchronized(this) {
System.out.println("synchronized");
}
}
}



Does this para mean to say that if we replace "this" operator with any third party object, then we will have two locks

One is the lock of the object which was used to invoke the method and
the other was the third party object

Am i correct ?

Regards
sid
 
Henry Wong
author
Marshal
Pie
Posts: 21220
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does this para mean to say that if we replace "this" operator with any third party object, then we will have two locks


You will have one lock -- you will replace the lock from the "this" object with the lock from another object.

One is the lock of the object which was used to invoke the method and
the other was the third party object


There is no lock need to invoke the method -- the method isn't synchronized. (which BTW, if the method is syschronized, it would have used the "this" object)

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic