Author | Topic: Marcus Exam#2 Q42 |
Howard Stern ranch hand |
posted March 31, 2000 05:11 PM
The answer given are 2,3 and 4. My second doubt: Answer 3) can a thread obtain a mutually exclusive lock on a method OR should it be object? If so then should the answer be reworded as " A thread can obtain a mutually exclusive lock on an object when the object invokes a method which has the keyword synchronized". I have read the JLS on this topic and haven't really got any convincing answer.Does anyone recommend a better source to study threads?
|
Just For A Moment greenhorn |
posted April 01, 2000 04:54 AM
Hi, For Option 2) the locks are associated with objects and not with methods. So even if an object doesnt have any method synch/unsynch, its possible to lock it. e.g. class A { int[] a; void aMethod() { Option 3) Your interpretation is right. U can refer to "Java Threads" by O'Rielly Pub.
|
maha anna bartender |
posted April 01, 2000 06:51 AM
Howard, Regarging lock of an object 1.Each object has a mutually exclusive lock.
2.lock is associated with objects NOT methods. 3.when you put 'synchronized' keyword before a instance method you are obtaining the lock of 'this' object which is the current object. Eventhough it looks like the METHOD is synchronized.
4.every object has a Class object associated with it. when you put synchronized keyword on a class method what it is doing is , the lock associated with the 'Class' object is obtained. (i.e)
[This message has been edited by maha anna (edited April 01, 2000).]
|
Howard Stern ranch hand |
posted April 01, 2000 05:01 PM
Thanx Maha and "JFAM". When I posted the question I think I forgot that there are two things a) synchronized statements and b) synchronized methods. A thread can acquire a lock on any object through a synchronized statement as shown in Maha's example in point 1). However a thread CANNOT acquire a lock on any object through a synchronized method it can only obtain a lock on the this object i.e the object of the class in which the method is defined or any object that is an instance of the subclass of the class in which the method is defined. If the class in question is static then the lock associated with the 'Class' object is obtained. Thought I would add this just to be more complete. [This message has been edited by Howard Stern (edited April 02, 2000).]
|
| | |