Think about a scenario where you would have to find at run time that whether a java thread has lock on a particular object e.g. find out whether thread NewsReader has lock on NewsPaper object or not ?

2 ways to find if thread holds lock on object in Java
Here I am giving my answer and what I had discovered after interview
1)I thought about IllegalMonitorStateException which wait() and notify() methods throw when they get called from non-synchronized context so I said I would call newspaper.wait() and if this call throws exception it means thread in java is not holding lock, otherwise thread holds lock.
2)Later I discovered that thread is a static method called holdsLock(Object obj) which returns true or false based on whether threads holds lock on object passed.
Comments, Suggestions ,innovative better answers are always welcome.
Other Java Threading tutorial you may like:
Tidak ada komentar:
Posting Komentar