-2

In java can we define synchronized block inside a synchronized method? If so please explain me with example

  • 1
    What happens when you try it? Are you facing any problems or does it work as expected? – Pshemo Mar 11 '18 at 19:19
  • 1
    Yes, but you probably shouldn't. If you're locking the same thing, that's extra code for no effect. If you're locking two things, then you run the risk of dead lock. If you must lock more than one object, then you must impose a total order on the locks. A synchronized method is unlikely to do this. https://en.wikipedia.org/wiki/Dining_philosophers_problem – markspace Mar 11 '18 at 19:22
  • The answer to the linked duplicate is really good by the way. The OP should read it to gain some more insight into why and when to do this. – markspace Mar 11 '18 at 19:34

1 Answers1

0

That is very much possible:

public class Locker {
    private final Object lock = new Object();
    synchronized void something() {
        synchronized (lock) {
            // tada
        }
    }
}

The usefulness of this is questionable though. This feels like it increases the risk of deadlocks by a huge margin.

luk2302
  • 55,258
  • 23
  • 97
  • 137