简体   繁体   中英

Java 8 - ReentrantLock/Locking an object

I'm wondering if using a ReentrantLock is the solution for my problem; I'm trying to "lock"(prevent other threads from accessing/using it) an object until a certain operation is complete, and then unlock it so other threads can access it. I thought of using sun's Unsafe#monitorEnter/exit but that could cause a deadlock.

Imagine the following situation:

public void doSomething() {
    Object object = someObject;

    // Object should be locked until operation is complete.
    doSomethingElse(object);

    // Object should now be unlocked so other threads can use/access it.
}

public void doSomethingElse(Object object) {
    // Something happens to the object here
}

Would this be the solution?

  ReentrantLock reentrantLock = new ReentrantLock();

  public void doSomething() {
        Object object = someObject;

        // Object should be locked until operation is complete.
        reentrantLock.lock();
        doSomethingElse(object);

        reentrantLock.unlock();

        // Unlock object for other threads after complete.
    }

    public void doSomethingElse(Object object) {
        // Something happens to the object here
    }

Thanks in advance.

I would recommend to use a synchronized method on doSomethingElse instead

public void doSomething() {
    Object object = someObject;

    // Object should be locked until operation is complete.
    doSomethingElse(object);
    // Unlock object for other threads after complete.
}

public synchronized void doSomethingElse(Object object) {
    // Something happens to the object here
}

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