6

Why does the Object class have thread-related methods, like wait(), notify(), notifyAll()?

We need to extend Thread or implement Runnable to give Thread-like behavior to a class. So why weren't they made part of any Thread or Runnable object?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
sri_sankl
  • 223
  • 4
  • 13
  • This question isn't really conclusively answerable by more than a very small group of people. The reason is that someone somewhere at some point for some reason decided to make every object a condition variable. – millimoose May 09 '13 at 08:00

2 Answers2

5

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

1) Wait and notify are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object as it is the superclass of all Objects.

2) Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • why dint java provide an interface for this functionality? Why did it have to be Object class and force this functionality on all objects when there might be cases where all execution is done in a single thread – MozenRath Jan 01 '14 at 21:16
0

If a thread has locked on an object instance, calling notify on that object instance will wake up those threads. So, since a lock is an object instance, operations related to that lock belong to the object instance.

Mirko Adari
  • 5,083
  • 1
  • 15
  • 23