需要知道对象锁定信息
在java中,我创建了一个具有全局作用域的对象。
在某些时候,我位于不同的线程中,需要知道全局对象当前是否被任何线程锁定。
- 克里希纳
In java, I have created an object with global scope.
At some point I am in a different thread and need to know whether the global object is currently locked by any threads.
- Krishna
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在普通对象上使用同步关键字是不可能的。
您需要一个“锁”对象,也许是一个实现 java.lang.concurrent.locks.Lock,它提供了 tryLock() 方法或类似方法。
这允许您的线程尝试获取锁,如果该锁当前未在其他地方锁定,则返回 true。
当然,在这种情况下,您可能需要立即解锁锁 - 否则您的线程将阻止其他线程取得进展。
This is not possible using the synchronized keyword on ordinary Objects.
You need a "lock" object, perhaps one implementing java.lang.concurrent.locks.Lock, which offers a tryLock() method or similar.
This allows your thread to attempt to acquire the lock, returning true if the Lock is not currently locked elsewhere.
Of course, in this case, you may then need to unlock the lock immediately - otherwise your thread will prevent other threads from making progress.
这里的大问题是定义“当前”。
我能建议的最好的办法是尝试以零超时获取锁。如果您获得了锁,则可以确定全局对象已被您的“不同线程”锁定。如果不是,则该对象可能已被其他线程锁定或未被锁定,也可能是,但在返回失败的锁定尝试时该锁可能已被释放。如果您在锁定尝试期间将“不同线程”的优先级提高到尽可能高,您应该能够获得更可靠的结果。
如果此测试用于临时调试、优化或统计目的,那么很好,但您不应该使用类似的东西来实现可交付的功能。
平均值,
马丁
The big problem here is defining 'currently'.
The best I can suggest is to try to acquire the lock with a zero timeout. If you get the lock, you are sure that the global object is locked - by your 'different thread'. If not, the object may be locked or not by some other thread, probably it is, but the lock may have been released while your failed lock attempt was returning. You should be able to get more reliable results if you raise the priority of your 'different thread' to the highest possible during your lock attempt.
If this test is for some temporary debugging, optimization or statistical purpose then fine, but you should not use anything like this to implement deliverable functionality.
Rgds,
Martin