aspose file tools*
The moose likes Threads and Synchronization and the fly likes synchronized(ObjectInstance){ //satements } AND Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronized(ObjectInstance){ //satements } AND Polymorphism" Watch "synchronized(ObjectInstance){ //satements } AND Polymorphism" New topic
Author

synchronized(ObjectInstance){ //satements } AND Polymorphism

Harish Tiruvile
Ranch Hand

Joined: Dec 01, 2005
Posts: 99
Hi,

while studying Synchronization in java i came across following CODE I am having dout with analysing this code.

Object ObjectInstance = new Object( );
synchronized(ObjectInstance){ //statements ..}

Say for example:
i have created one application in which i have created 10 classes(from Class1,Class2........Class10)...in one class i have used Synchronized block
Class1 class1 = new Class1( );
synchronized(class1){ //Statements ..}

this block will acquire lock for Class1 class. i.e, no body can call Class1 class methods or update instance variables until Synchronized block finishes its job..

if this analysis is correct then what about the following code:

Object ObjectInstance = new Object( );
synchronized(ObjectInstance){ //Statements ..}

Which class acquire lock when i execute above code.Will polymorphism concepts comes here.I mean, Since Class1 ,Class2 ....class10 extends Object Class will all classes (from Class1,Class2........Class10) acquire lock due to polymorphism when i execute above code ...will that mean i cant acess Class1,Class2........Class10 Classes methods until syncronization block finishes its task....

Please clarify my dout if you know the answers...i have searched for answer in google but i did not got any information adout this Particular dout.

Thanks for your guidence in Advance
Bye

[ April 11, 2006: Message edited by: harish thrivile ]
[ April 11, 2006: Message edited by: harish thrivile ]

Giving up is the easiest thing in the world to do..but holding it together when everything seems like falling apart is true strength!!
with regards, Harish.T
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

i have created one application in which i have created 10 classes(from Class1,Class2........Class10)...in one class i have used Synchronized block
Class1 class1 = new Class1( );
synchronized(class1){ //Statements ..}

this block will acquire lock for Class1 class. i.e, no body can call Class1 class methods or update instance variables until Synchronized block finishes its job..


This is *not* true. Acquiring a lock for the Class1 object does not prevent other threads from calling its methods or updating its instance variables. It merely prevents other threads from also acquiring the lock of the same instance, while this block is holding the lock.

Sorry if I am making a correction that you already know... but the distinction is important. Don't want other people reading this, to misinterpret.


BTW... I am not sure what you mean by the second part of your question... could you clarify?

Henry
[ April 11, 2006: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Harish Tiruvile
Ranch Hand

Joined: Dec 01, 2005
Posts: 99
Hi Henry Wong ,

Yes you are absolutely right....sorry for my mistake....

BTW... I am not sure what you mean by the second part of your question... could you clarify?


While reading some program in Internet i found the following code which i am feeling difficult to analyze
we know that " Synchronized block prevents other threads from also acquiring the lock of the same instance" .
so

class A
{
//
//
//statements
....
}

class B extends A
{
//
//
//statements
....
}

public class C
{
A a = new A();
public void someMethod()
{
synchronized(a)
{
//statements
}
}

Above code will prevents other threads acquiring the lock on the " a " instance ( in this case ) until the thread which is executing above code completes its task.....

if that right then what happens in below code

In the following example i am creating instance an instance of Object class say globalMonitor.
*************************************
private static final Object globalMonitor = new Object();

public void open() throws RecordStoreException
{
synchronized (globalMonitor)
{
while (isOpen(name))
{
try {
globalMonitor.wait();
}catch (InterruptedException e) {}
}
markOpen(_name);
}

What i am thinking is no other thread can acquire lock on Object class instance "globalMonitor" until the thread which is executing the above Synchronized block completes its task.......
If that analysis is correct then can you tell me significance of getting lock for Object class....

In first example i am getting lock for class A instance .....because i felt i have some code which should be protected from other thread while current thread is executing (doing some crucial modifications)..
But what is the use on Synchronizing Object class ...
1)Do we have crucial data in Object class...
2)Otherwise this" Object class " instance in Synchronized block is preventing other thread acquiring lock on its child class .i mean does polymorphism concept comes here like
Object class instance in above code "globalMonitor" can be any class which extends Objects class (Obviously every class extends Object class)..
if that is the case we acquiring lock on all objects when one thread enters a syncronized block .......I am sure this analysis is not correct...........

so please explain me how to analyze code when it is taking Object class instance in synchronized block like this
public void someMethod()
{
Object obj = new Object();

Synchronized(obj)
{

//How to analyze this block which takes Object class Instance
}


}
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40


private static final Object globalMonitor = new Object();

public void open() throws RecordStoreException
{
synchronized (globalMonitor)
{
while (isOpen(name))
{
try {
globalMonitor.wait();
}catch (InterruptedException e) {}
}
markOpen(_name);
}

What i am thinking is no other thread can acquire lock on Object class instance "globalMonitor" until the thread which is executing the above Synchronized block completes its task.......
If that analysis is correct then can you tell me significance of getting lock for Object class....


First, there is no significance in using an Object class. It can use any object as the lock... and the developer decided to just create one.

Second, take a look at the wait() method. You will see that the lock is actually released. So yes, it will prevent other threads from grabbing the lock while in the synchronized block -- but not for the period in the wait() method.

Henry
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

In first example i am getting lock for class A instance .....because i felt i have some code which should be protected from other thread while current thread is executing (doing some crucial modifications)..
But what is the use on Synchronizing Object class ...
1)Do we have crucial data in Object class...
2)Otherwise this" Object class " instance in Synchronized block is preventing other thread acquiring lock on its child class .i mean does polymorphism concept comes here like
Object class instance in above code "globalMonitor" can be any class which extends Objects class (Obviously every class extends Object class)..
if that is the case we acquiring lock on all objects when one thread enters a syncronized block .......I am sure this analysis is not correct...........


Oh... I think I am starting to understand... sorry if I misinterpreted the question.

When you synchronize on an object, you will prevent other threads from synchronizing on the same instance. It will have absolutely no affect on other threads that are synchronizing on other object instances -- whether these objects are instantiated from the same class, from child classes, or any other classes.

Henry
Padma Lalwani
Ranch Hand

Joined: Nov 02, 2004
Posts: 49
Yes, I think you are referring to synchronized method as opposed to synchronized object
Only one thread can work on a synchronized method of a class at a given time, and this method level locking holds true even if the synchronized method is inherited from parent class

Whereas in object synchronization, only the given object is locked, other object instances of same class, parent class, subclass etc, can still be used by different threads
Andreas Schaefer
Ranch Hand

Joined: Feb 13, 2006
Posts: 63

Yes, I think you are referring to synchronized method as opposed to synchronized object
Only one thread can work on a synchronized method of a class at a given time, and this method level locking holds true even if the synchronized method is inherited from parent class


That is not quite true. A synchronized method is locked on the instance and not on the class. The two code snippets are equivalent below:



If it would be the case that sychronized methods would lock on the class then calling a method on a java.util.Vector would automatically lock out all the other instances of this class even when the have nothing to do with the other vector.

-Andy
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Unless it's a *static* synchronized method, of course.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Padma Lalwani
Ranch Hand

Joined: Nov 02, 2004
Posts: 49
Thanks for the correction and sorry for the confusion! Anyhow I am trying again.

With synchronized keyword on the method, the default lock is on the current object the method belongs to, with exclusive access to its data. But other threads can execute the same synchronized method on different object instances.

And something like this in a class
<<
private static final Object globalMonitor = new Object();
and synchronized (globalMonitor) {}
>>
is used to prevent concurrent access to the code within the synchronized block, by different threads, even on different object instances. This can be acheived by a static synchronized method too. And as before in addition it locks the current object instance too.

Correct me if I am wrong, Padma
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Not disagreeing with anything here... just clarifying.

For simplicity, it is easier to just say when threads are synchronizing using the same instance, they will block -- allowing only one thread to own the lock at any given time.

It is also easier not to develop another technique to understand synchronized methods -- instead related it to the objects. For instance methods, the object is the instance itself. For static methods, the object is the class object (accessed either by the getClass() method with an instance, or via the ".class" variable given a static context). With this object, apply the rule for synchronization of objects.

Henry
Harish Tiruvile
Ranch Hand

Joined: Dec 01, 2005
Posts: 99
Thank you Henry Wong for clearing my dout

When you synchronize on an object, you will prevent other threads from synchronizing on the same instance. It will have absolutely no affect on other threads that are synchronizing on other object instances -- whether these objects are instantiated from the same class, from child classes, or any other classes.


In case of ordinary methods(non static methods):
Say for example we are having 2 instance of Object class
Object obj1 = new Object();
Object obj2 = new Object();

Then acquiring lock on obj1 does not prevent from getting lock on instance obj2 even though it belongs to same class

In case of static methods:
Say for example we are having 2 instance of a class StaticClassDemo
which is having static method
public Class StaticClassDemo
{
public static void staticMethod()
{
//
}

}
StaticClassDemo inst1 =new StaticClassDemo();
StaticClassDemo inst2 =new StaticClassDemo();

public void someMethod()
{
Synchronized(inst1)
{
//statements
}
}

since we are having static method in Class StaticClassDemo does that mean :: if one Thread acquire lock on inst1 (instance of same class ) then no other thread can acquire lock on another instance of StaticClassDemo i.e on inst2 ...just because we are having static method inside StaticClassDemo class (since static method is one per class not one per instance) ...

If that is wrong then will that staticMethod( ) be THREAD SAFE !!

Correct me if it is wrong.

[ April 12, 2006: Message edited by: harish thrivile ]
[ April 12, 2006: Message edited by: harish thrivile ]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

The following code ...



is equivalent to this code...



Noticed that the object being used as a lock is *not* the same as the "this" object for regular methods.

So... synchronizing a instance method have no relationship lock-wise with synchronizing a static method.

Henry
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

StaticClassDemo inst1 =new StaticClassDemo();
StaticClassDemo inst2 =new StaticClassDemo();

public void someMethod()
{
Synchronized(inst1)
{
//statements
}
}

since we are having static method in Class StaticClassDemo does that mean :: if one Thread acquire lock on inst1 (instance of same class ) then no other thread can acquire lock on another instance of StaticClassDemo i.e on inst2 ...just because we are having static method inside StaticClassDemo class (since static method is one per class not one per instance) ...


"inst1" is one object. "inst2" is another object. And "StaticClassDemo.class" is a third object. They are different objects. What happens depend on which lock you grab -- or even more than one lock that you grab.

Henry
 
 
subject: synchronized(ObjectInstance){ //satements } AND Polymorphism