Hari Krishna Hari Krishna - 1 month ago 31
Java Question

is reentrant lock is complete replacement for synchronisation?

I gone through the article "http://www.ibm.com/developerworks/java/library/j-jtp10264/".They mentioned that "The Lock framework is a compatible replacement for synchronisation". I understood that by using Reentrant locks we can hold the lock across the methods, wait for the lock for certain period of time (It is not possible using synchronised block (or) methods). My doubt is, is it possible to replace the application with synchronisation mechanism with Reentrant locks?

For example, I want to implement a thread safe stack data structure, where all the push, pop, getTop methods are synchronised, so in multi threaded environment, only one thread can able to access one synchronised method at a time (If one thread is using push method, no other threads can able to access push, pop, getTop (or) any other synchronised methods of Stack class). Is it possible to implement same thread safe stack data structure using Reentrant lock? If possible, please provide an example to understand this.

Answer

The answer is "Yes".

lock - unlock pair used instead of synchronize( ) { ... }. await and signal in Condition is replacement for wait and notify.