Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency in Java: synchronized static methods

I want to understand how locking is done on static methods in Java.

let's say I have the following class:

class Foo {
    private static int bar = 0;
    public static synchronized void inc() { bar++; }
    public synchronized int get() { return bar; }

It's my understanding that when I call f.get(), the thread acquires the lock on the object f and when I do Foo.inc() the thread acquires the lock on the class Foo.

My question is how are the two calls synchronized in respect to each other? Is calling a static method also acquires a lock on all instantiations, or the other way around (which seems more reasonable)?


EDIT:

My question isn't exactly how static synchronized works, but how does static and non-static methods are synchronized with each other. i.e., I don't want two threads to simultaneously call both f.get() and Foo.inc(), but these methods acquire different locks. My question is how is this preventable and is it prevented in the above code.

like image 451
Amir Rachum Avatar asked Mar 26 '11 15:03

Amir Rachum


Video Answer


1 Answers

If you read http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html.

It will tell you:

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

which tells you all you need to know.

like image 153
bmargulies Avatar answered Oct 25 '22 00:10

bmargulies