Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Object.wait() final?

Tags:

java

In Java, what is the reason behind Object's wait() method being implemented as a final method? Is there no need for overriding wait()?

like image 353
ms07 Avatar asked Dec 26 '13 20:12

ms07


2 Answers

The Java Language Specification describes how synchronization works. Among the many concepts, like object monitors, there's also the concept of Wait Sets.

Every object, in addition to having an associated monitor, has an associated wait set. A wait set is a set of threads.

When an object is first created, its wait set is empty. Elementary actions that add threads to and remove threads from wait sets are atomic. Wait sets are manipulated solely through the methods Object.wait, Object.notify, and Object.notifyAll.

If you were able to override the method, you might find yourself with a way to break synchronization. Java can not allow that. It has to have control over the exact implementation, which is why it is final.

like image 66
Sotirios Delimanolis Avatar answered Dec 18 '22 21:12

Sotirios Delimanolis


We call wait(), notify() or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:

  1. IllegalMonitorStateException in Java which will occur if we don't call wait(), notify() or notifyAll() method from synchronized context.
  2. Any potential race condition between wait and notify method in Java.

Hence, I guess it would not be a good idea to let override wait()

See more in Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition).

like image 24
aviad Avatar answered Dec 18 '22 22:12

aviad