How can we create the `notify ()` method in an object?

I was asked this question in an interview.

How you can create your own notify() method ?

I said that this is a method nativeand cannot be overridden.

But she was not happy with the answer.

Can someone explain?

+4
source share
2 answers

I assume that the interviewer wanted to implement a Java version of something equivalent to a waiting / notification mechanism, without using Object.wait () and Object.notify () directly.

For example, any of the following high-level synchronization mechanisms can be used to simulate wait / notify:

  • Implementing BlockingQueue
  • SynchronousQueue
  • CountDownLatch
  • CyclicBarrier
  • Futures

, , /. /, , , , "" , .

, SynchronousQueue:

public class WaitNotify {
  private final Object ITEM = new Object(); 
  private final SynchronousQueue<Object> q = new SynchronousQueue<Object>();

  public void myNotify() {
    q.offer(ITEM);
  }

  public void myWait() throws InterruptedException {
    q.take();    
  }
}
+1

( , JVM), -, , , . -, . obj, , , (.. obj), runnable, , . , , , .

0

Source: https://habr.com/ru/post/1532276/


All Articles