• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why all methods like wait(),notify(),notifyAll() are defined in Object class

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Last time with the discussion of with my colleagues I stucked at point .All threads can only use wait,notify,notifyAll methods but still why they are defined in Object class.
I am not clear with the explanation .Can anyone with the suitable reason.

Sumit
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sumit Tiwari wrote:Hi All,

Last time with the discussion of with my colleagues I stucked at point .All threads can only use wait,notify,notifyAll methods



You can use those methods on any object to use it as a signal between threads. You generally should not use those methods on a Thread object because they have special uses within the Thread class that can cause inconsistency. Since you use these methods to communicate between threads, conceptually putting the methods in the Thread interface does not sit well with me: you would have to explicitly create your Thread objects and pass them around and between all your other Threads so you can communicate between them. This is awkward and would make it hard to use thread pools safely.

Instead you should use those methods either on a dedicated 'lock' Object, or on a particular Object whose data is being shared between threads. This gives you more control over the synchronization tasks and aligns the synchronization scheme to data being protected. Since the 'data being protected' can be any type, and since you can synchronize on any Object - and you need to be synchronized on the Object to signal with it, it makes sense that these methods should be implemented in the Object class - so that no matter what type of data you are protecting you can use it for locking and synchronization.

I personally think these methods and synchronization should be isolated to dedicated Classes used for this purpose (like the java.util.concurrent.locks.Lock type). But barring that, it does not belong to the Thread interface.
reply
    Bookmark Topic Watch Topic
  • New Topic