Java - Thread Locks

Introduction

Explicit locking mechanism can be used to coordinate access to shared resources without using the keyword synchronized.

The Lock interface in the java.util.concurrent.locks defines the explicit locking operations.

ReentrantLock class is the implementation of the Lock interface.

The Lock interface is declared as follows:

public interface Lock {
        void lock();
        Condition newCondition();
        void lockInterruptibly() throws InterruptedException;
        boolean tryLock();
        boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
        void unlock();
}

The following code uses an Explicit Lock in its Simplest Form

Demo

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
        // Instantiate the lock object
        private Lock myLock = new ReentrantLock();

        public void updateResource() {
                // Acquire the lock
                myLock.lock();//from   w  ww . j  a va 2  s . co m

                try {
                        // Logic for updating/reading the shared resource goes here
                }
                finally {
                        // Release the lock
                        myLock.unlock();
                }
        }
}

Related Topics