1

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?

1
  • 2
    Why do you mean by locking an object? An object and a thread are two very different things. And once an object A has a reference to another object B, there is no way to prevent A from using B. Please explain what you want to do at a higher level. Commented Feb 8, 2012 at 15:27

2 Answers 2

1

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 synchronized keyword, which is the idiomatic way to do locking in Java. The Java concurrency tutorial has some material.

Sign up to request clarification or add additional context in comments.

Comments

1

This is not the pattern normally used but it could be used to prevent other threads from accessing the object. Other objects in the same thread could still access it.

As @rcook points out, this doesn't prevent other threads accessing the object unless they also attempt to acquire the lock.

If you make acquiring the lock and releasing it part of each method of the class, you can be sure there is no way to access the object without acquiring the lock. (Which is why this is usually recommended)

Is there any reason not to use the standard idiom for Lock here?

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html

1 Comment

I think you should mention that this does NOTHING to prevent other threads from accessing the object -- what it does it prevent other threads for getting a lock on the object. Only if other threads get a lock before they access it will it prevent access. I'm afraid the OP may not understand that the locking mechanism requires cooperation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.