Example usage for java.util.concurrent.locks Lock lock

List of usage examples for java.util.concurrent.locks Lock lock

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock lock.

Prototype

lock

Source Link

Usage

From source file:com.boylesoftware.web.impl.AbstractRouterConfiguration.java

@Override
public RouterRequest findRoute(final HttpServletRequest request, final HttpServletResponse response)
        throws MethodNotAllowedException, ServletException {

    // check if we have mappings
    if (this.mappings.length == 0)
        return null;

    // try to find the matching route mapping
    final Lock readLock = this.mappingsLock.readLock();
    readLock.lock();
    try {//w  w  w .j  a  v a 2  s.  c  o m

        // test request URI against the mappings
        RouteImpl mapping = this.mappings[0];
        final String requestURI = request.getRequestURI();
        // TODO: reusable matcher?
        final Matcher m = mapping.getURIPattern().matcher(requestURI);
        int mappingInd = 0;
        do {

            // try to match the mapping
            if (m.matches()) {

                // log the match
                if (this.log.isDebugEnabled())
                    this.log.debug("found mapping for URI " + requestURI + " on attempt " + (mappingInd + 1));

                // move the mapping higher if matched more frequently
                final long numMatched = mapping.incrementNumMatched();
                if (mappingInd > 0) {
                    final RouteImpl prevMapping = this.mappings[mappingInd - 1];
                    if (numMatched > prevMapping.getNumMatched()) {
                        final Lock writeLock = this.mappingsLock.writeLock();
                        readLock.unlock();
                        writeLock.lock();
                        try {
                            this.mappings[mappingInd] = prevMapping;
                            this.mappings[mappingInd - 1] = mapping;
                        } finally {
                            readLock.lock();
                            writeLock.unlock();
                        }
                    }
                }

                // wrap the request
                final RouterRequestImpl routerRequest = this.routerRequestPool.getSync();
                boolean success = false;
                try {

                    // initialize the router request
                    routerRequest.wrap(request, response, mapping, this.isAuthenticationRequired(requestURI));

                    // add parameters made from the URI components
                    final int numURIParams = m.groupCount();
                    for (int i = 0; i < numURIParams; i++) {
                        final String uriParamName = mapping.getURIParamName(i);
                        if (uriParamName != null)
                            routerRequest.addParameter(uriParamName, m.group(i + 1));
                    }

                    // convert flash attributes cookie to request attributes
                    routerRequest.flashCookieToAttributes();

                    // return the router request
                    success = true;
                    return routerRequest;

                } finally {
                    if (!success)
                        routerRequest.recycle();
                }
            }

            // next mapping for next iteration
            if (++mappingInd >= this.mappings.length)
                break;
            mapping = this.mappings[mappingInd];

            // reuse the matcher
            m.reset();
            m.usePattern(mapping.getURIPattern());

        } while (true);

    } finally {
        readLock.unlock();
    }

    // no mapping matched
    return null;
}

From source file:com.epam.jdi.uitests.web.selenium.driver.SeleniumDriverFactory.java

public WebDriver getDriver(String driverName) {
    if (!drivers.keys().contains(driverName))
        if (drivers.isEmpty())
            registerDriver("DEFAULT DRIVER", getDefaultDriver());
        else//w  w w  . j av  a  2s.c o  m
            throw exception("Can't find driver with name '%s'", driverName);
    try {
        Lock lock = new ReentrantLock();
        lock.lock();
        if (runDrivers.get() == null || !runDrivers.get().keys().contains(driverName)) {
            MapArray<String, WebDriver> rDrivers = runDrivers.get();
            if (rDrivers == null)
                rDrivers = new MapArray<>();
            WebDriver resultDriver = webDriverSettings.apply(drivers.get(driverName).get());
            if (resultDriver == null)
                throw exception("Can't get WebDriver '%s'. This Driver name not registered", driverName);
            rDrivers.add(driverName, resultDriver);
            runDrivers.set(rDrivers);
        }
        WebDriver result = runDrivers.get().get(driverName);
        if (result.toString().contains("(null)")) {
            result = webDriverSettings.apply(drivers.get(driverName).get());
            runDrivers.get().update(driverName, result);
        }
        lock.unlock();
        return result;
    } catch (Exception ex) {
        throw exception("Can't get driver; Thread: " + currentThread().getId() + LINE_BREAK
                + format("Drivers: %s; Run: %s", drivers, runDrivers) + "Exception: " + ex.getMessage());
    }
}

From source file:org.springframework.integration.redis.util.RedisLockRegistryTests.java

@Test
@RedisAvailable/*ww  w. j  a  v a 2s  . c om*/
public void testLock() throws Exception {
    RedisLockRegistry registry = new RedisLockRegistry(this.getConnectionFactoryForTest(), this.registryKey);
    for (int i = 0; i < 10; i++) {
        Lock lock = registry.obtain("foo");
        lock.lock();
        try {
            assertNotNull(TestUtils.getPropertyValue(registry, "hardThreadLocks", ThreadLocal.class).get());
        } finally {
            lock.unlock();
        }
    }
    assertNull(TestUtils.getPropertyValue(registry, "hardThreadLocks", ThreadLocal.class).get());
}

From source file:org.springframework.integration.redis.util.RedisLockRegistryTests.java

@Test
@RedisAvailable/*from  w w  w . j a v a 2  s .  c  om*/
public void testExpireNotChanged() throws Exception {
    RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest();
    final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000);
    Lock lock = registry.obtain("foo");
    lock.lock();

    Long expire = getExpire(registry, "foo");

    Future<Object> result = Executors.newSingleThreadExecutor().submit(() -> {
        Lock lock2 = registry.obtain("foo");
        assertFalse(lock2.tryLock());
        return null;
    });
    result.get();
    assertEquals(expire, getExpire(registry, "foo"));
    lock.unlock();
}

From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

public float[] getUserVector(String user) {
    Lock lock = xLock.readLock();
    lock.lock();
    try {//www.  ja v a 2  s. com
        return X.get(user);
    } finally {
        lock.unlock();
    }
}

From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

private ObjSet<String> doGetKnownItems(String user) {
    Lock lock = xLock.readLock();
    lock.lock();
    try {//  ww w .ja v  a2s.  c om
        return knownItems.get(user);
    } finally {
        lock.unlock();
    }
}

From source file:org.eclipse.gyrex.context.internal.registry.ContextRegistryImpl.java

/**
 * Returns the real context implementation
 * //w w  w  .j av a2s  . co  m
 * @param contextPath
 * @return
 * @throws IllegalArgumentException
 */
public GyrexContextImpl getRealContext(IPath contextPath) throws IllegalArgumentException {
    checkClosed();
    contextPath = sanitize(contextPath);

    // get existing context
    GyrexContextImpl context = null;
    final Lock readLock = contextRegistryLock.readLock();
    readLock.lock();
    try {
        context = contexts.get(contextPath);
        if (null != context)
            return context;
    } finally {
        readLock.unlock();
    }

    // hook with preferences
    getContextFlushNode().addPreferenceChangeListener(flushListener);

    // create & store new context if necessary
    final Lock lock = contextRegistryLock.writeLock();
    lock.lock();
    try {
        checkClosed();

        context = contexts.get(contextPath);
        if (null != context)
            return context;

        final ContextDefinition definition = getDefinition(contextPath);
        if (definition == null)
            throw new IllegalStateException(
                    String.format("Context '%s' does not exists.", contextPath.toString()));

        context = new GyrexContextImpl(contextPath, this);
        if (contexts.put(contextPath, context) != null)
            throw new IllegalStateException(String.format(
                    "Duplicate context object created for context '%s'. Please report stacktrace to the development team!",
                    contextPath.toString()));

    } finally {
        lock.unlock();
    }

    return context;
}

From source file:org.apache.lucene.gdata.search.index.IndexController.java

private void createNewDeleteAllEntriesTask(final ServerBaseFeed feed) {
    checkDestroyed();// w ww . j  a  v  a  2s  . co  m
    checkInitialized();
    if (LOG.isInfoEnabled())
        LOG.info("Deleting all entries for feed dispatch new IndexDocumentBuilder -- " + feed.getId());
    String serviceName = feed.getServiceConfig().getName();
    ServiceIndex bean = this.indexerMap.get(serviceName);
    if (bean == null)
        throw new RuntimeException("no indexer for service " + serviceName + " registered");
    Lock lock = bean.getLock();
    lock.lock();
    try {
        IndexDocumentBuilder<IndexDocument> callable = new IndexFeedDeleteTask(feed.getId());
        sumbitTask(callable, bean.getIndexer());
    } finally {
        lock.unlock();
    }

}

From source file:org.cyberjos.jcconf2016.node.HazelcastHelper.java

/**
 * Sets the given node to be the master node.
 *
 * @param cloudNode the node to become master
 * @return {@code true} if the given node becomes the master node
 *         successfully//from  ww  w.ja  v a2  s.  co  m
 * @throws NullPointerException if the given node is {@code null}
 */
public synchronized boolean setMaster(final CloudNode cloudNode) {
    Objects.requireNonNull(cloudNode, "The given cloud node must not be null.");

    final Lock lock = hazelcastHolder.getInstance().getLock("my-distributed-lock");
    lock.lock();

    try {
        final String nodeName = cloudNode.getName();
        final Optional<NodeRecord> optional = this.getMasterNodeRecord();
        logger.info("[{}] Ensure the master node: {}", nodeName, optional.orElse(null));

        if (optional.isPresent()) {
            final NodeRecord masterRecord = optional.get();
            final long count = hazelcastHolder.getInstance().getCluster().getMembers().stream()
                    .filter(member -> StringUtils.equals(masterRecord.getMemberId(), member.getUuid())).count();

            if (count != 0) {
                logger.warn("[{}] The master node has already existed: {}", nodeName, masterRecord);
                return false;
            }

            this.unregisterNode(masterRecord.getNodeName());
        }

        final NodeRecord newMasterRecord = HazelcastHelper.<String, NodeRecord>getMap(ACTIVE_NODES)
                .get(nodeName);
        HazelcastHelper.getAtomicReference(MASTER_NODE).set(newMasterRecord);
        logger.info("[{}] This node becomes the new master node: {}", nodeName, newMasterRecord);

        if (WORKING_MODE) {
            this.runProducer(cloudNode);
        }
    } finally {
        lock.unlock();
    }

    return true;
}

From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

/**
 * Prunes the set of users in the model, by retaining only users that are expected to appear
 * in the upcoming model updates, or, that have arrived recently. This also clears the
 * recent known users data structure.//  ww w . java 2s .c om
 *
 * @param users users that should be retained, which are coming in the new model updates
 */
void pruneX(Collection<String> users) {
    // Keep all users in the new model, or, that have been added since last model
    Lock lock = xLock.writeLock();
    lock.lock();
    try {
        X.removeIf(new KeyOnlyBiPredicate<>(new AndPredicate<>(new NotContainsPredicate<>(users),
                new NotContainsPredicate<>(recentNewUsers))));
        recentNewUsers.clear();
    } finally {
        lock.unlock();
    }
}