search

Home  >  Q&A  >  body text

多线程 - Java synchronized(t)的问题,如何知道某个对象t,是否被这样锁住了呢?

Java synchronized(t)这个关键字修饰的代码块,意思是说获得t的锁之后,才能运行代码块。那么问题来了,如何知道某个对象t,是否被这样锁住了呢?

PHPzPHPz2889 days ago323

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 17:55:17

    The Object class in the JDK does not provide an API to determine whether the object lock of an object is locked. But the following ideas may be feasible.

    The layout of an object in memory includes the following parts

    • Object Head

    • Object instance data (not concerned here)

    • Aligned padding (not concerned here)

    The object header contains some metadata of this object, including two parts: a mark word field and a klass field
    mark word contains a lock flag. When the object is not locked, the flag bit is 0 , otherwise it is 1.

    The size of mark word is also different on different platforms:

    For 32 bit JVM:
        _mark    : 4 byte constant
        _klass    : 4 byte pointer to class 
    
    For 64 bit JVM:
        _mark    : 8 byte constant
        _klass    : 8 byte pointer to class
    
    For 64 bit JVM with compressed-oops:
        _mark    : 8 byte constant
        _klass    : 4 byte pointer to class

    Therefore, as long as you can get the markword, you can get the lock flag, and then you can know whether an object is locked. However, in the JDK, we can only operate the instance data (variables and methods) of the object, and there is no way to get the object header of the object. Therefore, you may need to use the "black technology" in Javasun.misc.Unsafe.

    Take 32-bit jdk as an example:

    Object obj = new Object();
    int markword = unsafe.getInt(obj, 0L);

    The 0L here is the offset.
    Then perform a bit operation on the markword. The author needs to search for the specific content in the markword.

    Back to the poster’s question, maybe the poster just wants a way to know whether the lock is held, and does not necessarily have to contend with the question of whether the object t is synchronized.
    If so, then the poster can abandon the synchronized keyword and use ReentrantLock in juc ​​instead. There is a method to determine whether the lock is heldisLocked()

    reply
    0
  • Cancelreply