简体   繁体   中英

Check the Lock on an object in java

I want to check the lock on an object of the class. I use Thread.holdsLock(this) for this. Is this the Right way?

My question is how I can check if the object is locked for the main method and also check the lock on static methods.

public class CheckLock {
    public static void main(String[] args) throws InterruptedException {
        objectLockClass olc=    new objectLockClass();
        Thread t1=new Thread(olc);
        t1.start();
    }
}

class objectLockClass implements Runnable {

    @Override
    public void run() {
        boolean isLocked = true;
        int counter=0;     
        synchronized (this) {
            while (isLocked) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("lock object in run  : " + Thread.holdsLock(this));
                if (counter==5 ) isLocked=false;
                    counter++;
            }
        }

The output is:

lock object in run  : true
lock object in run  : true
lock object in run  : true
lock object in run  : true
lock object in run  : true
lock object in run  : true

how I can check the object is locked for main method and also check lock on static methods?

An object isn't locked for a method . It's just locked. period. The utility of Java's synchronized keyword is that no two threads will ever be allowed to synchronize on the same object at the same time.


It doesn't usually make sense to ask whether some other thread has an object locked. The Thread.holdsLock(foo) method won't tell you that: It only tells whether the calling thread has foo locked. Suppose there was a method, Thread.otherThreadHoldsLock(foo) , and suppose you called it like this:

Object foo = ...;

if (Thread.otherThreadHasLocked(foo)) {
    doSomething();
} else {
    doSomethingElse();
}

It doesn't give you any useful information: This code could call doSomething() with foo locked, or with foo not locked; and it could call doSomethingElse() with foo locked, or with foo not locked. There's no guarantee, because another thread could acquire the lock or release the lock at any time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM