以编程方式确定哪个Java线程持有锁 [英] Programmatically determine which Java thread holds a lock

查看:238
本文介绍了以编程方式确定哪个Java线程持有锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时可以通过编程方式检查持有给定对象的锁的Thread的名称。

Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?

推荐答案

您只能判断当前线程是否拥有正常锁定( Thread.holdsLock(Object) )。你不能获得有没有本地代码的锁的线程的引用。

You can only tell whether the current thread holds a normal lock (Thread.holdsLock(Object)). You can't get a reference to the thread that has the lock without native code.

但是,如果你在做线程复杂的事情,你可能想熟悉自己使用java.util.concurrent包。 ReentrantLock 允许您获取其所有者(但是它是受保护的方法,因此您必须扩展此方法)。根据你的应用程序,很可能是通过使用并发包,你会发现你不需要得到锁的所有者。

However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The ReentrantLock does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all.

是非编程方法来寻找锁所有者,例如发信号通知JVM发出线程转储到stderr,这对于确定死锁的原因是有用的。

There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks.

这篇关于以编程方式确定哪个Java线程持有锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆