0

It's said in this question that

there is no link between synchronized static methods and sync'ed non static methods

Ok, that's fairly plain, but what if code in a non-static method invokes static method? Will this thread hold both static(associated with class) and non-static (associated with an instance of a class) monitors?

Community
  • 1
  • 1
void
  • 731
  • 2
  • 11
  • 26
  • 5
    In general it is true that when from one `synchronized` block you enter another one (synchronizing on a different object), you'll have to acquire both monitors. (And if another part of the code tries to acquire the same two monitors in reverse order, bang, there's your deadlock.) – biziclop Nov 20 '15 at 09:49

2 Answers2

2

Will this thread hold both static(associated with class) and non-static (associated with an instance of a class) monitors?

Yes, and that is because,

as per Java Language Specification 8.4.3.6,

For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

And after all the 2 monitors will be defined separately.

coretechie
  • 1,050
  • 16
  • 38
  • You're [quoting the JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.3.6) here. You should certainly say so, both for proper attribution so as to avoid plagiarism charges, and to lend weight to your answer, and you should use quote formatting for text that is quoted. – user207421 Nov 20 '15 at 10:06
  • 'As per Java Language Specification 8.4.3.6' is not quoted text and shouldn't be so formatted. – user207421 Nov 20 '15 at 23:53
1

There isn't any such thing as "static synchronization" or "non-static synchronization". Those ideas hide what's really going on.

This:

class Foobar {
    static synchronized void mumble() { ... }
}

Is just a shortcut for writing this:

class Foobar {
    static void mumble() {
        synchronized(Foobar.class) {
            ...
        }
    }
}

And this:

class Foobar {
    synchronized void grumble() { ... }
}

Is just a shortcut for writing this:

class Foobar {
    void grumble() {
        synchronized(this) {
            ...
        }
    }
}

It doesn't make sense to talk about "static synchronization" because synchronization is something you do to an object, and there is no such thing as a static object. The only things in Java that can be static are variables and methods.


P.S., To answer your question,

When a thread enters a synchronized block or method, it must acquire the lock on the specified object if the thread does not already have that object locked. So if f.grumble() calls mumble() in my examples above, then the thread first must obtain the lock on f when it enters the grumble() routine, and then, while still holding that lock, it must also obtain the lock of Foobar.class.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57