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.