Java Object Class

Object class is not just plays the role of a super class for any class and also responsible for object locking, monitor entry and much more.

Following methods of Object class


Object wait method

If wait method without arguments invokes or calls, Then current thread will be releasing a lock on the Object of a particular class and stops the execution of further proceeding. The execution of a thread stops until the notify() or notifyAll() method is invoked on that particular object. As mentioned earlier, wait method can only be called in synchronized block otherwise it will leads to java.lang.IllegalMonitorStateException

Wait method example

public class Wait {

	public static void main(String[] args) throws InterruptedException {
		
		new Wait().waitExample();
	}
	
	public void waitExample() throws InterruptedException
	{
		synchronized (this) {
			this.wait();
			System.out.println("This will never be printed");
		}
	}

}
Output
Nothing gets printed...

Wait method with Notify Example

public class Wait {
	static Wait waitObject;
	public static void main(String[] args) throws InterruptedException {
		
		waitObject= new Wait();
		new Thread(new Runnable() {
			public void run() {
				try {
					waitObject.waitExample();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		Thread.sleep(100L);
		synchronized(waitObject) {
		System.out.println("Notify Going to be invoked");
		waitObject.notify();
		}
	}
	
	public void waitExample() throws InterruptedException
	{
		synchronized (waitObject) {
			waitObject.wait();
			System.out.println("This will be printed,as notify Called");
		}
	}

}
Output
Notify Going to be invoked
This will be printed,as notify Called