6

Possible Duplicate:
How do synchronized static methods work in Java?

I was wondering what would happen if synchronized was used on a static method. Does the class get a lock on that method? How is this different from synchronized on a non static method?

Thanks

Community
  • 1
  • 1
blaa
  • 63
  • 3
  • Synchronized static methods lock the class, as opposed to the object. http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html – CMR Mar 08 '11 at 00:05

1 Answers1

-1

Yes, the class "gets" the lock instead of the instance (as Bruno pointed out, this terminology is imprecise. The Thread gets the lock using either the class object or the instance as the locking object). Meaning, you could have 3 threads simultaneously executing 3 synchronized methods if those methods are synchronized on their individual instances. If the method is synchronized on the class, then only one thread can be executing it.

Kenny Wyland
  • 20,844
  • 26
  • 117
  • 229
  • So then what is the point of synchronizing non static methods? Sorry if this is a stupid question :S – blaa Mar 08 '11 at 00:03
  • Synchronizing an instance method protects against when two threads are trying to operate on the _same_ instance. Thread 1 and Thread 2 both have a reference to instance A. – Kenny Wyland Mar 08 '11 at 00:12
  • "the class gets the lock instead of the instance"?! A class does not ever get a lock. It is a thread that "gets" locks, and these are associated with objects. – Bruno Reis Mar 08 '11 at 02:37
  • 1
    @Bruno: and the object, in the case of a static method, is the *class object*. – Greg Hewgill Mar 08 '11 at 04:21
  • @Bruno, yes, I used imprecise terminology so that it was in the same terms the original poster used so that he/she would understand. Yes, the thread "gets" the lock. – Kenny Wyland Mar 08 '11 at 06:02