获取同步方法在 Java 中被阻塞的时间

Get the time a synchronized method has been blocked in Java

我有一个由不同线程调用的同步方法,其执行在对同一对象的方法的调用之间是互斥的。我想知道,在该方法被阻止的情况下,它被阻止的时间:

public class ManagerImpl implements Manager {

    public synchronized long entrarEnTramo() {
        movesomething()
        // This method must return long type with the time it has been blocked.
        // In the case it isn't blocked it returns -1.
    }

}

如果您可以更改此方法的源代码,则可以手动检测它

public long entrarEnTramo() {
    long started = System.nanoTime();
    synchronized (this) {
        long taken = System.nanoTime() - started;
        movesomething();
        return taken;
    }
}

但请注意,这并不能真正告诉您它是否被阻止,只是时间。 你大概可以从花费的时间上分辨出来。

如果没有,您将不得不 roll your own lock(然后您还可以实现锁定超时,synchronized 不提供)。