Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus mock exam #42

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of the following statements about threading are true
1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable
2) You can obtain a mutually exclusive lock on any object
3) A thread can obtain a mutually exclusive lock on a method declared with the keyword synchronized
4) Thread scheduling algorithms are platform dependent
The right answers are 2, 3, 4
I would like to know why answer 2 is right as i feel that u need to have snchronized method or code to get a lock.
thanks
maala
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maala,
Though using a synchronized method is a popular practice, one can achieve a finer granularity of thread-safetyness by synchronizing only a part of the code. Here you will use the synchronize(object) syntax

Occasionally, it is useful to lock an object and obtain exclusive access to it for just a few instructions without writing a whole new synchronized method. Synchronized blocks are slightly more efficient than synchronized methods as they save an additional method call.
Hope this helps,
Ajith
 
kevin jia
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,Ajith
I have two questions as follow:
No1: I think answer 3) is not right. The concept of "block" is belong to object, not belong to method. Could you explain it.
No2: For the code you provide, here I write it again
public void someMethod() {
//lots of code here
synchronized(someObject) {
//synchronized code
}
//lots of other code here
}
If someObject means "this", I can understand. But if it means someObject of other type, I want to know why we do like this,
we obtain lock on one object, but we operate the code on another object. Could you give me a practical example.
Thanks Ajith
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks ajith!!! for ur explanation
maala
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic