0

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();
}
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • 1
    Yes, it's better in general, because it means no other code can synchronize on the same monitor. This is a common practice - I'm slightly surprised it's not in Effective Java... – Jon Skeet Jul 12 '17 at 05:50
  • A recommendation I read the other days mentions it is better to have the lock object to not be part of the class but to be constructed outside and passed into the synchronized object i.e. `public void fun(Object monitor)` – Scary Wombat Jul 12 '17 at 05:53
  • see https://stackoverflow.com/questions/44919393/how-to-achieve-synchronization-of-threads-using-synchronized-method-in-java – Scary Wombat Jul 12 '17 at 05:57
  • @JonSkeet It is, toward the end of Item 70. – shmosel Jul 12 '17 at 05:57
  • @shmosel Thanks for pointing out Item 70. I always like to use that book as golden reference. – Cheok Yan Cheng Jul 12 '17 at 06:03

0 Answers0