The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
July 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


RE:synchronize a static method

Posted by Kishori Sharan on July 27, 2000 at 11:06 AM

Hi Raghu
In java, objects are always created on heap. If you have a static object for a class ( i.e. a class object which is defined static ) then the object reference is created in "Static storage" section ( this is also a part of RAM and variable are alive as long as program runs ) , but the object itself is created on heap. e.g.

class Abc {
static MyClass myobject = new MyClass ( ) ;
Here the myobject is object reference which holds the reference of the actual object in memeory and it is stored in static storage. However, "new MyClass ( )" allocates the actual memeory for the object on heap. So, myobject in static storage is pointing to the memory in heap allocated by "new MyClass ( ) ". Now if you are using synchonized static method to access the myobject then it depends on which thread has lock on it. Even if you have may objects of the same class ( MyClass ) created by different threads then they cannot access myobject concurrently ( assuming that synchronization is used ). One more thing , you can only synchronize a method or a section of a code. You cannot say that this class object/varibale is synchonized. So if you make that class object public and static then you can access that object from any no. of threads without any problem. However, this is not often desirable ( to make class/object's object/variable public ) because you don't want to read/write the same variable concurently.


> Hello Kishori Sharma,

> Thanx a lot.
> I like to know one thing!
> Since Static objects are class objects...,
> does a static method uses same memory place
> for all the objects of that class ?.
> If that is the case I presume that....
> in the previous senario,
> all the objects of that class should wait until the
> lock is released by the current thread.Am I correct !?.

> thanx in advance.
> raghu

> > Hi
> > a. Can we synchronize a static method
> > Ans: Yes. You can synchronize a static method.
> > b. if YES what is its effect in multi threading environment.
> > Ans: If one thread is executing a static synchronized method of a class then it holds a lock on all other syncronized methods of that class and in effect no other thread can call any of the synchonized static methods of that class untill this current thread releases the lock.
> > c. if NO why
> > Ans: ---

> >
> > Thanx
> > Kishori


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us