Reputation: 69
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.
Upvotes: 3
Views: 651
Reputation: 5506
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.
Upvotes: 1
Reputation: 41985
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
}
}
Upvotes: 3
Reputation: 272367
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.
Upvotes: 3
Reputation: 533780
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.
Upvotes: 1