Reputation: 2951
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.
Upvotes: 1
Views: 1118
Reputation: 19185
You have below options
But there is no need that B should know that A has the lock , once lock is released it will be available for B to use if there aren't any threads waiting on it.
Upvotes: 1
Reputation: 718826
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.
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 Lock
interface similarly doesn't support this.
The ReentrantLock
class does provide a method to find this out: see ReentrantLock.getOwner()
. Note however that this is a protected
method, so you'd need to create a subclass of ReentrantLock
if 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.
Upvotes: 1
Reputation: 22890
Which lock are you talking about? If it is a ReentrantLock for instance, you can just call
lock.getOwner()
Edit:
synchronized(xObj) { }
Is not a lock as you are implying. It is conceptually closer to a monitor lock. You have limited functionality using synchronized blocks, and that's exactly why classes like ReentrantLock exists.From the doc
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
Upvotes: 0
Reputation: 33534
- When a thread gets the lock
of an object, then all the synchronized
methods can only be accessed through that thread and none, till it leaves the lock.
- If Thread A
has the lock
of an object and Thread B
tries to access the lock on the same object, it can't access
it. As the lock is with A, its Not important for Thread B ,that lock is with whom, but is the lock available. If not Thread B moves into blocked state till the lock is released by Thread A.
Upvotes: 0