Determine which thread owns a monitor

前端 未结 4 1346
有刺的猬
有刺的猬 2020-12-06 01:50

Is there a way to tell, for a Java object, which Thread (or null) currently owns its monitor? Or at least a way to tell if the current thread owns it?

4条回答
  •  误落风尘
    2020-12-06 02:35

    The java classes monitor is internal to the JVM and you cannot really play with it.

    If you know that the object is locked, you can try to obtain the monitor again - if you can get it, it means that you're locking the object from your thread (because java locks are recursive - you can lock twice from the same thread). The problem is that you cannot try to synchronize.

    You can use the unsafe object to do that. unsafe has a tryMonintorEnter() method that does just that. see unsafe.

    Unsafe might be able to actually help you get the thread that holds the monitor, but I don't know how to do that...

提交回复
热议问题