This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
All Objects and classes have locks. Is this true.. I know, Objects can have locks and how abt classes?? I remember, this has been discussed here , sometime back, but, I could not follow it that time. can anyone throw some light on this??
All objects have locks. Here you go for a nice ride into the JLS JLS 17.13 Locks and Synchronization Let's take an example: We have the following declaration somewhere: SomeClass someObject = new SomeClass(); For instance, when you want to lock on an object, you just have to write the following code:
Classes also have a lock. In order to lock on a class, you write the following code:
Note that SomeClass.class resolves to the Class object representing the class of someObject and not the file in which someObject is declared. Class objects are unique within all JVMs, that is there is only one instance of each Class loaded in any JVM. [ August 16, 2002: Message edited by: Valentin Crettaz ]
"NO JLS.. Only VAL".. Thanks Val... Thats a nice explanation again!!
Joined: May 27, 2002
But Val, where exactly , we can use synchronized(SomeClass.class).. Can I get a example from you!!
Joined: Aug 26, 2001
synchronizing on the class has the same effect has declaring a static method synchronized, that is only one thread will ever be able to access any object of the same class at the same time, which is not always the case with object locks if there are different objects and threads are locking on different objects. I will give you an example later. If somebody else has one ready, just post it and we will discuss it. In the meantime, Murthy, try to come up with one example of your own and we will go into it. Practice is your best teacher