Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why wait() and notify() are not in special class? [closed]

Tags:

java

wait

notify

Why are wait, notify and notifyAll methods placed in Object, not in some separated class?

Note, this question is not about moving them to Thread class, I just wonder why does they litter Object, not some new Monitor class.

I see the following shortcomings of that idea:

  • We won't be able to use our for-other-purpose fields as monitors. But this seems to agree with principle of modularity.
  • Synchronized methods will now require some hack with generated hidden fields (like in closures), as this and <MyClass>.class become not valid monitors.

So we could move away 5 methods from every object with a little woe. Or not?

like image 337
Martoon Avatar asked Feb 16 '16 11:02

Martoon


2 Answers

The real answer is that it was a mistake, finally acknowledged with the creation of the Condition class, which does exactly what you'd expect. (Although since it is an object, there is a possibility that you'll accidentally invoke wait() on it instead of await(), with hilarious consequences...)

Apart from the things you've already listed, tying a monitor to every single object also makes it impossible to have truly immutable objects in Java.

So you can do this for example:

class A {
   void foo() {
      synchronized((Integer)42) {
         ...
      }
   }
}

class B {
   void foo() {
      synchronized((Integer)42) { 
          ...
      }
   }
}

Returning the same boxed integer for 42 every time shouldn't be a problem if the object was immutable. But it isn't, it has a mutable state: its monitor, making this kind of synchronization possible. What's particularly evil in this is that you've created a mutex between two pieces of code that on the face of it appear to be independent.

like image 192
biziclop Avatar answered Oct 21 '22 03:10

biziclop


One advantage of this is that you can simply synchronize on a reference without creating a redundant monitor for it:

synchronized (myList) {
    myList.add(0);
}

vs

private final Object mySpecialMonitor = new Object();

syncronized(mySpecialMonitor) {
    myList.add(0);
}

It would not work if all synchronization was in a separate class.

like image 27
AdamSkywalker Avatar answered Oct 21 '22 03:10

AdamSkywalker