So in Java I know that you can use the so-called "intrinsic lock" of objects to create mutual exclusion regions as well as to ensure memory visibility. Java makes it particularly easy to implicitly lock on the intrinsic lock of the this
object with some syntax sugar like:
public class Foo{
public synchronized doFoo(){
//doFoo is executed in an implicit synchronized block
//on the 'this' object
}
}
This is understandable and accepted practice for guarding the member fields of many objects. What I don't know is whether the above is okay when the object being locked on is a Thread
object. E.g., are there any reasons to avoid the following?
public class Bar extends Thread{ //notice the 'extends Thread' here
public synchronized doBar(){
//doBar is executed in an implicit synchronized block
//on the 'this' object
}
}
For now, I'm going to stick with something I know is more safe, e.g.:
public class Baz extends Thread{ //notice the 'extends Thread' here
private final Object explicitLockObject = new Object();
public doBaz(){
synchronized(explicitLockObject){
//doBaz impl
}
}
}
My concerns would be two-fold with option #2 (the Bar
example):
- Is there existing jvm code or Java convention regarding synchronizing on the Thread itself that might conflict with such a locking policy?
- Locking on
this
generally implies that access of that object should always be guarded by that object's intrinsic lock. In the case of aBar
thread, that means we're implying that any time you touch aBar
thread, you should synchronize on the instance. That seems like it could end up causing some other thread to block unnecessarily (or even dangerously) untilBar
completes/exits.
Are the above valid concerns? I feel like I need a Brian Goetz beacon for this one :-)