Lock application-Try Lock acquisition

Source: Internet
Author: User

When a thread requests an internal lock, if the lock is occupied, the request thread must wait unconditionally, which often causes many strange problems. Waiting for each other is one of the important causes of deadlock, the famous philosopher's dining problem is a typical case. The new Lock provides the tryLock () method to automatically give up when an attempt is made to obtain the Lock fails, providing a better error recovery mechanism.


boolean tryLock();boolean tryLock(long time, TimeUnit unit) throws InterruptedException;


The Lock interface defines two reload tryLock () functions. The first function indicates that if the Lock is available, the Lock is obtained immediately and true is returned. If the requested Lock is unavailable, the Lock is immediately abandoned and false is returned; the second function indicates that if the requested lock is currently available, the lock will be obtained immediately and true will be returned. If the lock is unavailable, the lock will wait for the specified time. During the waiting period, the thread may be interrupted and the lock may be obtained, if the lock is not obtained at the end of the wait time, the system automatically gives up and returns false. Obviously, the first function provides more flexibility.


Of course, we can also use loop round robin to call tryLock () to implement polling locks and so on to implement more flexible mechanisms. This is the advantage of Lock over internal locks, especially when the thread needs to obtain multiple different locks at the same time, tryLock () is very useful.


For example, in a simple application scenario, assume that we have a scheduled task to clean up garbage regularly, but the time consumed by each garbage cleanup may be different, if the new task finds that the previous task has not been completed, it will end on its own because this task is not required. In fact, the ScheduledExecutorService. scheduleAtFixedRate () function provides this function. Each scheduled task is executed only after the previous task is completed.


import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class TestTryLock {    private Lock mLock;    private volatile boolean isTimeoutEnabled;                                                         public TestTryLock(){        this.mLock = new ReentrantLock();        this.isTimeoutEnabled = false;    }                                                         public void clearRubbish() throws InterruptedException{        if(mLock.tryLock()){            try{                System.out.println(Thread.currentThread().getName() + ":get the lock successfully.");                int estTime = (int) (10 * Math.random());                System.out.println(Thread.currentThread().getName() + ":estimate time for finish job:" + estTime);                TimeUnit.SECONDS.sleep(estTime);            }            finally{                mLock.unlock();            }                  }        else{            System.out.println(Thread.currentThread().getName() + ":failed to get the lock.");        }          }                                                         public void clearRubbishWithTimeout() throws InterruptedException{        if(mLock.tryLock(2, TimeUnit.SECONDS)){            try{                System.out.println(Thread.currentThread().getName() + ":get the lock successfully by waiting 2 seconds.");                int estTime = (int) (10 * Math.random());                System.out.println(Thread.currentThread().getName() + ":estimate time for finish job:" + estTime);                TimeUnit.SECONDS.sleep(estTime);            }            finally{                mLock.unlock();            }                  }        else{            System.out.println(Thread.currentThread().getName() + ":failed to get the lock after waiting 2 seconds.");        }          }                                                         private class Worker implements Runnable{        @Override        public void run() {            try {                if(isTimeoutEnabled){                    clearRubbishWithTimeout();                }                else{                    clearRubbish();                }                                                                                   isTimeoutEnabled = !isTimeoutEnabled;            } catch (InterruptedException e) {                e.printStackTrace();            }        }          }                                                         private class TimerWorker implements Runnable{        @Override        public void run() {            new Thread(new Worker()).start();        }          }    public static void main(String[] args) {        TestTryLock testTryLock = new TestTryLock();        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);        service.scheduleAtFixedRate(testTryLock. new TimerWorker(), 0, 3, TimeUnit.SECONDS);           }}




This article is from "the power comes from the sincere love !" Blog, please be sure to keep this source http://stevex.blog.51cto.com/4300375/1301077

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.