3

I have a class

class Foo{

    static synchronized get(){}
    synchronized() getMore(){}
}

I have 2 objects Foo.get() and f.getMore() running in 2 different threads t1 and t2. i had a dobuts whether when thread t1 had got a lock on the class can thread t2 access the method getMore or would t2 be prevented from getting the access and the lock to the method since the class object is locked by t1.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
user1954799
  • 69
  • 1
  • 2
  • possible duplicate of [Concurrency in Java: synchronized static methods](http://stackoverflow.com/questions/5443297/concurrency-in-java-synchronized-static-methods) – bmargulies Jan 07 '13 at 23:09

4 Answers4

3

The static method will synchronise on the Class object as opposed to the instance object. You have 2 locks operating on 2 different objects. In your scenario above there will be no blocking behaviour.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

Static Synchronized ---> Class Level Locking (Class level scope)

it is similar to

synchronized(SomeClass.class){
 //some code
}

Simple Synchronized ---> Instance level locking

Example:

class Foo{

     public static synchronized void bar(){
         //Only one thread would be able to call this at a time  
     }

     public synchronized void bazz(){
         //One thread at a time ----- If same instance of Foo
         //Multiple threads at a time ---- If different instances of Foo class
     }

}
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
1

synchonized locks an object and a static synchronized locks the object which represents the class.

t1 and t2 can call these methods concurrently except they cannot both be in the static synchronized method unless all but one thread is wait()ing.

Note: t1 and t2 can call getMore() at the same time for different objects.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

The synchonized static method will aquire the lock Of java.lang.Class object which is assosiated on behalf of Foo class.

The synchonized instance method will aquire the lock of Actual object.

NPKR
  • 5,368
  • 4
  • 31
  • 48