Code example for Lock

Methods: tryLock, unlock

0
 
    public boolean trySendOnSharedLine(String message, long timeout, TimeUnit unit)
            throws InterruptedException { 
    	 
        long nanosToLock = unit.toNanos(timeout)  - estimatedNanosToSend(message);
        if (!lock.tryLock(nanosToLock, NANOSECONDS))
            return false; 
        try { 
            return sendOnSharedLine(message);
        } finally { 
            lock.unlock();
        } 
    } 
 
    private boolean sendOnSharedLine(String message) {
        /* send something */ 
        return true; 
    } 
 
    long estimatedNanosToSend(String message) {
        return message.length();