Bhatnag
Bhatnag

Reputation: 31

How does a lock work in Java?

Suppose I have 2 instances of a CustomThread and one common object instance called printer. Inside the print method of printer, if I do a lock.lock() and lock.unlock() at the end, how does this work?

private class Printer{

        private final Lock mutex = new ReentrantLock(true);

        public void print(int thread){
            try {
                mutex.lock();
                for(int i = 0; i < 10; ++i) {
                    System.out.println(String.format("Printing: %d for Thread: %d", i, thread));
                }
            } catch(Exception e){

            } finally {
                mutex.unlock();
            }
        }
    }

I will call this method from 2 of my thread objects.

My question is, how does the method lock itself? Isn't a lock based on a thread? Maybe I am confusing the core idea here. When I do a lock inside a method, what does it mean?

Upvotes: 0

Views: 145

Answers (1)

erickson
erickson

Reputation: 269637

You can think of it as if a lock has a field called owner, which is a Thread.

When lock() is called, and owner is null, owner is assigned to the calling thread. When unlock() is called, owner is reset to null.

When lock() is called, and owner is not null (and not the current thread, since the lock is re-entrant), the calling thread blocks until another thread relinquishes ownership and it can be assigned as the new owner.

The additional complication is that the check for the current ownership, and the conditional assignment of the current thread as the new owner, both have to be seen to occur atomically by other threads. This preserves the integrity of the lock.

Upvotes: 4

Related Questions