Tuesday, 27 March 2018

Difference between final, finally and finalize()?

final :Final is a keyword.
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.

finally:Finally is a block.
Finally is used to place important code, it will be executed whether exception is handled or not.

finalize: Finalize is a method.
Finalize is used to perform clean up processing just before object is garbage collected.

Why wait(), notify() and notifyAll() must be called from synchronized block or method in Java


We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.

One thread is waiting after checking a condition .Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and now all the threads which are waiting, fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further.

which could lead to potential race condition and now how to  resolved it? This race condition is resolved by using synchronized keyword and locking provided by Java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method.

Since the wait() method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait() method, we must use this lock to ensure that checking the condition  and setting the condition is atomic which can be achieved by using synchronized method or block in Java.

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...