0

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.

  • 5
    That would only work if all other code using the object will use the same lock. Why not use `synchronize (object) { doSomethingElse(object); }`? Of course, other code will still have to synchronize too. – Andreas Jul 16 '18 at 21:54
  • Didn't think of that solution. However, imagine a situation where I don't have control over other code that accesses the object, what would be a good solution for this if there are any? – leapinglasagne Jul 16 '18 at 22:07
  • If you don't have control over other code, then you can't prevent them from accessing the object. There is no solution. – Andreas Jul 16 '18 at 22:24

1 Answers1

0

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
}
D. Mayen
  • 424
  • 3
  • 8
  • Would this still be effective if I don't have control over other code that accesses the object? I literally don't want anything to be able to touch the specified object when the #doSomethingElse operation is running. Third party applications shouldn't be able to touch the object until the operation is complete; that's my goal. – leapinglasagne Jul 16 '18 at 22:18
  • @leapinglasagne Only the object itself can protect it correctly from all use of it. – Andreas Jul 16 '18 at 22:25
  • @Andreas What about sun's Unsafe monitor enter/exit? – leapinglasagne Jul 16 '18 at 22:49