I was wondering, when designing a class which is safely accessed by multiple threads, is using synchronized around object instance itself, a good practice?
public class Foo {
public synchronized void fun() {
}
}
One of the side effect is that, when caller uses the class instance in the following way, it will blocks other threads from accessing foo.fun()
Caller tries to use the class instance as thread monitor
Foo foo = new Foo();
// This will have side effect, which blocks other threads from accessing foo.fun()
synchronized(foo) {
}
I was wondering, is using a private final Object
instance as internal thread monitor in Foo
class, a safer & better way?
public class Foo {
public void fun() {
synchronized (monitor) {
}
}
private final Object monitor = new Object();
}