zentenk
zentenk

Reputation: 2815

locking object java

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?

Upvotes: 1

Views: 147

Answers (2)

NPE
NPE

Reputation: 500673

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

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

Upvotes: 1

Related Questions