File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes lock on method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "lock on method?" Watch "lock on method?" New topic

lock on method?

Yi Dong

Joined: May 19, 2003
Posts: 22
Hi All:
Here is the question:
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
I think only 2, 4 are correct, but the ans are 2, 3, 4.
Is there any lock on a method ? Can somebody explain this ?
Thanks in advance !
Yi Dong
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
Only oblects and classes have locks, methods don't.
JLS, Chapter 17.13:

There is a lock associated with every object.
The synchronized statement (�14.18) computes a reference to an object; it
then attempts to perform a lock action on that object and does not proceed further until the lock action has successfully completed.

JLS, Chapter synchronized Methods
A synchronized method acquires a lock (�17.1) before it executes. For a class (static) method, the lock associated with the Class object for the method�s class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.

Synchronizing Threads Sun Tutorial

The code segments within a program that access the same object from separate, concurrent threads are called critical sections. In the Java language, a critical section can be a block or a method and are identified with the synchronized keyword. The Java platform then associates a lock with every object that has synchronized code.

[ November 24, 2003: Message edited by: Vad Fogel ]
[ November 24, 2003: Message edited by: Vad Fogel ]
I agree. Here's the link:
subject: lock on method?
It's not a secret anymore!