Example usage for java.util.concurrent.locks ReentrantLock tryLock

List of usage examples for java.util.concurrent.locks ReentrantLock tryLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock tryLock.

Prototype

public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been Thread#interrupt interrupted .

Usage

From source file:netflix.archaius.SampleApplication.java

/**
 * SampleApplication entrypoint/*from w w  w  . jav  a  2s .c o  m*/
 * @param args
 * @throws InterruptedException 
 * @throws IOException 
 */
public static void main(String[] args) throws InterruptedException, IOException {
    //@SuppressWarnings(value = {"unused" })
    new SampleApplication();

    // Step 1.
    // Create a Source of Configuration
    // Here we use a simple ConcurrentMapConfiguration
    // You can use your own, or use of the pre built ones including JDBCConfigurationSource
    // which lets you load properties from any RDBMS
    AbstractConfiguration myConfiguration = new ConcurrentMapConfiguration();
    myConfiguration.setProperty("com.netflix.config.samples.sampleapp.prop1", "value1");
    myConfiguration.setProperty("com.netflix.config.samples.SampleApp.SampleBean.name",
            "A Coffee Bean from Gautemala1");

    // STEP 2: Optional. Dynamic Runtime property change option
    // We would like to utilize the benefits of obtaining dynamic property
    // changes
    // initialize the DynamicPropertyFactory with our configuration source
    DynamicPropertyFactory.initWithConfigurationSource(myConfiguration);

    // STEP 3: Optional. Option to inspect and modify properties using JConsole
    // We would like to inspect properties via JMX JConsole and potentially
    // update
    // these properties too
    // Register the MBean
    //
    // This can be also achieved automatically by setting "true" to
    // system property "archaius.dynamicPropertyFactory.registerConfigWithJMX"
    configMBean = ConfigJMXManager.registerConfigMbean(myConfiguration);

    // once this application is launched, launch JConsole and navigate to
    // the
    // Config MBean (under the MBeans tab)
    System.out.println("Started SampleApplication. Launch JConsole to inspect and update properties");
    System.out.println(
            "To see how callback work, update property com.netflix.config.samples.SampleApp.SampleBean.sensitiveBeanData from BaseConfigBean in JConsole");

    SampleBean sampleBean = new SampleBean();
    System.out.println("SampleBean:" + sampleBean);
    System.out.println(sampleBean.getName());

    System.setProperty("archaius.fixedDelayPollingScheduler.initialDelayMills", "100");
    System.setProperty("archaius.fixedDelayPollingScheduler.delayMills", "100");
    //       System.setProperty("archaius.configurationSource.defaultFileName", "log4j.properties");
    //       ConfigurationManager.loadCascadedPropertiesFromResources("log4j");

    FixedDelayPollingScheduler f = new FixedDelayPollingScheduler(100, 100, true);

    // create a property whose value is type long and use 1000 as the default 
    // if the property is not defined
    System.setProperty("archaius.fixedDelayPollingScheduler.initialDelayMills", "100");
    System.setProperty("archaius.fixedDelayPollingScheduler.delayMills", "100");
    System.setProperty("archaius.configurationSource.defaultFileName", "log4j.properties");
    ConfigurationManager.loadCascadedPropertiesFromResources("log4j");

    // create a property whose value is type long and use 1000 as the default 
    // if the property is not defined
    DynamicLongProperty timeToWait = DynamicPropertyFactory.getInstance().getLongProperty("lock.waitTime",
            1000);
    ReentrantLock lock = new ReentrantLock();

    // ...
    while (true) {
        lock.tryLock(timeToWait.get(), TimeUnit.MILLISECONDS); // timeToWait.get() returns up-to-date value of the property
        System.out.println("??" + timeToWait.get());
        Thread.sleep(1000);

        //              AbstractConfiguration myConfiguration = new ConcurrentMapConfiguration();
        //               myConfiguration.setProperty("lock.waitTime", 11);
        //               DynamicPropertyFactory.initWithConfigurationSource(myConfiguration);
        //               System.out.println( "??"+timeToWait.get());

    }

}

From source file:de.unirostock.sems.cbarchive.web.dataholder.Workspace.java

@JsonIgnore
public synchronized Lock lockArchive(String archiveId) throws CombineArchiveWebException {

    if (archives.containsKey(archiveId) == false)
        throw new CombineArchiveWebException("No such archive.");

    ReentrantLock archiveLock = null;
    synchronized (this) {
        archiveLock = locks.get(archiveId);
        if (archiveLock == null) {
            archiveLock = new ReentrantLock(true);
            locks.put(archiveId, archiveLock);
        }//from  w ww  .  ja va 2 s .  c o  m
    }

    try {
        if (archiveLock.tryLock(Fields.LOCK_ARCHIVE_TIMEOUT, TimeUnit.SECONDS) == false)
            throw new CombineArchiveWebException("Lock timeout.");
    } catch (InterruptedException e) {
        throw new CombineArchiveWebException("Lock interrupted.", e);
    }

    return archiveLock;
}

From source file:com.zimbra.cs.db.SQLite.java

@Override
void preOpen(Integer mboxId) {
    ZimbraLog.dbconn.trace("trying to lock mbox %d", mboxId);
    assert (checkLockMap(mboxId));
    ReentrantLock lock = lockMap.get(mboxId);
    if (lock == null) {
        lock = new ReentrantLock();
        ReentrantLock added = lockMap.putIfAbsent(mboxId, lock);
        if (added != null) {
            lock = added;//from  w  w w .j ava  2s .  co m
        }
    }
    boolean locked = false;
    long timeoutSecs = 180;
    //lock with timeout in case external call sites cause a deadlock
    //(e.g. one site locks some object before opening connection; another incorrectly locks same object after opening connection)
    //in case of timeout we'll fall through and let sqlite_busy retry handler sort it out
    try {
        locked = lock.tryLock(timeoutSecs, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    if (!locked) {
        ZimbraLog.dbconn.warn("Unable to get db lock for mbox %d", mboxId);
    } else {
        ZimbraLog.dbconn.trace("locked mbox %d", mboxId);
    }
}

From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProvider.java

private <K> K tryLockAnd(ConcreteResource resource, long timeout, TimeUnit unit, TransferLockTask<K> task)
        throws IOException {
    ReentrantLock lock = getTransferLock(resource);
    boolean locked = false;
    try {//from  w w  w  .j a va 2  s.  c  o m
        if (timeout > 0) {
            locked = lock.tryLock(timeout, unit);
            if (locked) {
                return task.execute(resource);
            } else {
                throw new IOException(
                        String.format("Did not get lock for resource %s in %d %s, timeout happened.", resource,
                                timeout, unit.toString()));
            }
        } else {
            lock.lockInterruptibly();
            return task.execute(resource);
        }

    } catch (InterruptedException e) {
        logger.warn("Interrupted for the transfer lock with resource: {}", resource);
        return null;
    } finally {
        if (timeout <= 0 || locked) {
            lock.unlock();
        }
    }
}

From source file:org.apache.hadoop.hive.ql.Driver.java

/**
 * Acquires the compile lock. If the compile lock wait timeout is configured,
 * it will acquire the lock if it is not held by another thread within the given
 * waiting time./*w w w. j  a  v  a  2  s . c o  m*/
 * @return the ReentrantLock object if the lock was successfully acquired,
 *         or {@code null} if compile lock wait timeout is configured and
 *         either the waiting time elapsed before the lock could be acquired
 *         or if the current thread is interrupted.
 */
private ReentrantLock tryAcquireCompileLock(boolean isParallelEnabled, String command) {
    final ReentrantLock compileLock = isParallelEnabled ? SessionState.get().getCompileLock()
            : globalCompileLock;
    long maxCompileLockWaitTime = HiveConf.getTimeVar(this.conf, ConfVars.HIVE_SERVER2_COMPILE_LOCK_TIMEOUT,
            TimeUnit.SECONDS);

    final String lockAcquiredMsg = "Acquired the compile lock.";
    // First shot without waiting.
    try {
        if (compileLock.tryLock(0, TimeUnit.SECONDS)) {
            LOG.debug(lockAcquiredMsg);
            return compileLock;
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Interrupted Exception ignored", e);
        }
        return null;
    }

    // If the first shot fails, then we log the waiting messages.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Waiting to acquire compile lock: " + command);
    }

    if (maxCompileLockWaitTime > 0) {
        try {
            if (!compileLock.tryLock(maxCompileLockWaitTime, TimeUnit.SECONDS)) {
                errorMessage = ErrorMsg.COMPILE_LOCK_TIMED_OUT.getErrorCodedMsg();
                LOG.error(errorMessage + ": " + command);
                return null;
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Interrupted Exception ignored", e);
            }
            return null;
        }
    } else {
        compileLock.lock();
    }

    LOG.debug(lockAcquiredMsg);
    return compileLock;
}