-1

Can anyone tell me which one is better approach between synchronization method and private final object in java and why ??

public class kclass {

    private final Object myObject = new Object();

    public synchronized void show() {
       ...
    } 

    public void show1() {
        synchronized(myObject) {
            ...
        } 
    }
}
3
  • 1
    ??? synchronized and private do completely different things. What actual problem are you trying to solve? Could you please edit your question with more background?
    – amon
    Commented Nov 22, 2018 at 18:31
  • Recommended reading: Open letter to students with homework problems. "If your question... is just a copy paste of homework problem, expect it to be downvoted, closed, and deleted - potentially in quite short order."
    – gnat
    Commented Nov 22, 2018 at 21:19
  • @amon: the distinction is between synchronized method() { ... } and method() { synchronize (obj) { ... } } with a private final Object obj; Commented Nov 23, 2018 at 4:41

1 Answer 1

3

In general both approaches are legit. Using a dedicated object to synchronize on allows you to do more fine-grained synchronization than using synchronized on the method level: you may synchronize only part of a method or use different lock objects for different synchronization purposes. synchronized (non static) methods will implicitly synchronize on the object they are called on, so their whole body is synchronized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.