Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

lock on method?

 
Yi Dong
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 8.4.3.6:

8.4.3.6 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic