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) {
  • 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 Nov 22 '18 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 Nov 22 '18 at 21:19
  • @amon: the distinction is between synchronized method() { ... } and method() { synchronize (obj) { ... } } with a private final Object obj; – Hero Wanders Nov 23 '18 at 4:41

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, privacy policy and cookie policy

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