I have a question on normal java threading theory.
Thread A has taken a lock on some object, let say xObj. Now how does Thread B know that Thread A has already taken a lock on object xObj.
How this has been implemented in java.
Thanks in advance.
Thanks for your answers….Here i would like to clear that…I don’t have to implement this.My concern is How Java has implemented that.How Thread B will get to know that someone has already taken a lock on Object.May be Object class or some other class has implemented this.
It depends on the kind of lock you are talking about.
For a primitive mutex, one thread cannot test if another thread holds the mutex, let alone find out which thread it is. (It can test if holds the lock however …)
The
Lockinterface similarly doesn’t support this.The
ReentrantLockclass does provide a method to find this out: seeReentrantLock.getOwner(). Note however that this is aprotectedmethod, so you’d need to create a subclass ofReentrantLockif you wanted to make the method generally available.I would also question the value of such a method. It can only tell you which (if any) thread owns the lock at the instant that the call was made. An instant later, the owner could have changed.
By constrast,
Thread.holdsLock()gives you information that you can rely on … albeit that it is information that isn’t useful under most circumstances.