Tuesday 23 September 2014

Lock interface

Just like synchronized methods and synchronized blocks, Lock provides synchronization mechanism. Lock implementations provide more extensive locking operations than synchronized methods and blocks.

ReentrantLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock implements Lock interface.

Methods in Lock interface
Method Description
void lock() Acquires the lock. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.
void lockInterruptibly() Acquires the lock if it is available and returns immediately. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:


a. The lock is acquired by the current thread; or
b. Some other thread interrupts the current thread, and interruption of lock acquisition is supported.
Condition newCondition() Returns a new Condition instance that is bound to this Lock instance.
boolean tryLock() Acquires the lock only if it is free at the time of invocation. Returns true if the lock was acquired and false otherwise.
boolean tryLock(long time, TimeUnit unit) Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted. Returns true if the lock was acquired and false if the waiting time elapsed before the lock was acquired.
void unlock() Releases the lock.

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

public class Task implements Runnable{
    
   int taskNum;
   static Lock myLock = new ReentrantLock();
   
   Task(int taskNum){
       this.taskNum = taskNum;
   }
    
   @Override
   public void run(){
       myLock.lock();
       try {
           System.out.println(taskNum +" Started ");
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException ex) {
               
           }
           System.out.println(taskNum +" Finished ");
        }
       finally {
          myLock.unlock();
       }
    }
}

public class LockEx {
    public static void main(String args[]){
        int taskNum = 1;
        
        while(taskNum < 50){
            Task task = new Task(taskNum);
            new Thread(task).start();
            taskNum++;
        }
    }
}

Output
1 Started 
1 Finished 
2 Started 
2 Finished 
3 Started 
3 Finished 
4 Started 
4 Finished 
6 Started 
6 Finished 
5 Started 
5 Finished 




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment