I have an object that I would like to lock.
class TestObj {
Lock lock = new Lock();
public void lockObj {
lock.lock();
}
public void unlockObj {
lock.unlock();
}
// other methods/attributes omitted
}
class Test {
public static void main(String[] args) {
TestObj testObj = new TestObj();
testObj.lockObj();
}
}
Would this lock the TestObj object? So that other objects/threads cannot access this particular TestObj?
It would lock the object in the sense that any other thread will block (that is, wait) if it tries to call
lockObj().If another thread simply jumps in and starts accessing the object without calling
lockObj(), there’s nothing to stop it.At this point, I would encourage you to read up on the
synchronizedkeyword, which is the idiomatic way to do locking in Java. The Java concurrency tutorial has some material.