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

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

Introduction

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

Prototype

void unlock();

Source Link

Document

Releases the lock.

Usage

From source file:be.fgov.kszbcss.rhq.websphere.connector.security.TrustStoreManager.java

public void execute(TrustStoreAction action, boolean readOnly) throws Exception {
    Lock lock = readOnly ? truststoreLock.readLock() : truststoreLock.writeLock();
    lock.lock();/*from  w  w w  .j a  va 2s .c  o  m*/
    try {
        KeyStore truststore = loadTrustStore();
        action.execute(truststore);
        if (!readOnly) {
            if (log.isDebugEnabled()) {
                log.debug("Writing trust store with " + truststore.size() + " entries to " + truststoreFile);
            }
            OutputStream out = new FileOutputStream(truststoreFile);
            try {
                truststore.store(out, new char[0]);
            } finally {
                out.close();
            }
            reloadTrustManager();
        }
    } finally {
        lock.unlock();
    }
}

From source file:net.gbmb.collector.RecordController.java

private void addRecord(String cid, CollectionRecord record) throws CollectionStateException {
    Lock lock = hazelcast.getLock(cid);
    lock.lock();/* www  .j  a  v a 2 s  . c om*/
    try {
        Collection collection = collectionMap.get(cid);
        if (collection == null) {
            throw new CollectionStateException("Collection not existing");
        } else if (collection.getState() != CollectionState.COLLECTING) {
            throw new CollectionStateException(collection.getState(), "Collection not in collecting state");
        } else {
            collectionRecords.put(cid, record);
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.pepstock.jem.gwt.server.services.RolesManager.java

/**
 * Returns a collection of roles, by a filter (a set of key-values).
 * //from   ww  w. j a  va 2 s  .c o m
 * @param filter
 *            string which contains a set of key-values
 * @return a collection of roles, matching the filter
 * @throws ServiceMessageException
 *             if any exception occurs
 */
public Collection<Role> getRoles(String filter) throws ServiceMessageException {
    // checks if the user is authorized to read roles
    // if not, this method throws an exception
    checkAuthorization(new StringPermission(Permissions.ROLES_READ));

    IMap<String, Role> roles = getInstance().getMap(Queues.ROLES_MAP);
    RolePredicate predicate;
    try {
        // creates predicate by filter string
        predicate = new RolePredicate(Filter.parse(filter));
    } catch (Exception e) {
        LogAppl.getInstance().debug(e.getMessage(), e);
        // default case, all roles
        Filter all = new Filter();
        all.add(new FilterToken(RoleFilterFields.NAME.getName(), StringUtils.EMPTY));
        predicate = new RolePredicate(all);
    }

    List<Role> list = null;
    // locks all map to have a consistent collection
    // only for 10 seconds otherwise
    // throws an exception
    boolean isLock = false;
    Lock lock = getInstance().getLock(Queues.ROLES_MAP_LOCK);
    try {
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // applies predicate
            list = new ArrayList<Role>(roles.values(predicate));
        } else {
            throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, Queues.ROLES_MAP);
        }
    } catch (InterruptedException e) {
        throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, e, Queues.ROLES_MAP);
    } finally {
        // unlocks always the map
        if (isLock) {
            lock.unlock();
        }
    }
    return list;
}

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

/**
 * Prunes the set of items in the model, by retaining only items that are expected to appear
 * in the upcoming model updates, or, that have arrived recently. This also clears the
 * recent known items data structure./*from   w ww .  j a v a  2s. com*/
 *
 * @param items items that should be retained, which are coming in the new model updates
 */
void pruneY(Collection<String> items) {
    for (int partition = 0; partition < Y.length; partition++) {
        // Keep all items in the new model, or, that have been added since last model
        Lock lock = yLocks[partition].writeLock();
        lock.lock();
        try {
            Y[partition].removeIf(new KeyOnlyBiPredicate<>(new AndPredicate<>(new NotContainsPredicate<>(items),
                    new NotContainsPredicate<>(recentNewItems[partition]))));
            recentNewItems[partition].clear();
        } finally {
            lock.unlock();
        }
    }
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onFailure(HttpResponse)}.</p>
 *  /*w w w .  j ava  2 s. c o  m*/
 * @since 1.3.0
 */
@Test
public final void testAsyncFailure() throws InterruptedException {

    String subpath = "/asyncfailure", body = "hello";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(403).withBody(body)));

    final Object[] content = new Object[1];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncFailure(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {
        }

        @Override
        public void onFailure(HttpResponse httpResponse) {

            lock.lock();

            content[0] = httpResponse;
            condition.signal();

            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
}

From source file:DemandCache.java

/**
 * @see java.util.Map#entrySet()/* ww w .  j a  va2  s.  c  o  m*/
 */
public Set<java.util.Map.Entry<K, V>> entrySet() {
    Lock lock = theLock.writeLock();
    lock.lock();
    final Map.Entry<K, CacheValue>[] entries;
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        entries = theCache.entrySet().toArray(new Map.Entry[0]);
    } finally {
        lock.unlock();
    }
    return new java.util.AbstractSet<Map.Entry<K, V>>() {
        @Override
        public java.util.Iterator<Map.Entry<K, V>> iterator() {
            return new java.util.Iterator<Map.Entry<K, V>>() {
                int index = 0;

                public boolean hasNext() {
                    return index < entries.length;
                }

                public Map.Entry<K, V> next() {
                    Map.Entry<K, V> ret = new Map.Entry<K, V>() {
                        private final int entryIndex = index;

                        public K getKey() {
                            return entries[entryIndex].getKey();
                        }

                        public V getValue() {
                            return entries[entryIndex].getValue().value;
                        }

                        public V setValue(V value) {
                            V retValue = entries[entryIndex].getValue().value;
                            entries[entryIndex].getValue().value = value;
                            return retValue;
                        }

                        public String toString() {
                            return entries[entryIndex].getKey().toString() + "="
                                    + entries[entryIndex].getValue().value;
                        }
                    };
                    index++;
                    return ret;
                }

                public void remove() {
                    DemandCache.this.remove(entries[index - 1].getKey());
                }
            };
        }

        @Override
        public int size() {
            return entries.length;
        }
    };
}

From source file:net.solarnetwork.node.io.rxtx.RxtxDataCollectorFactory.java

@Override
public ConversationalDataCollector getConversationalDataCollectorInstance(SerialPortBeanParameters params) {
    Lock lock = acquireLock();
    try {// w  w w.  j av a  2  s.c  o  m
        CommPortIdentifier portId = getCommPortIdentifier();
        // establish the serial port connection
        SerialPort port = (SerialPort) portId.open(params.getCommPortAppName(), 2000);
        SerialPortConversationalDataCollector obj = new SerialPortConversationalDataCollector(port,
                params.getMaxWait());
        setupSerialPortSupport(obj, params);
        return new PortLockedConversationalDataCollector(obj, portId.getName(), lock);
    } catch (PortInUseException e) {
        lock.unlock();
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        lock.unlock();
        throw new RuntimeException(e);
    } catch (RuntimeException e) {
        lock.unlock();
        throw e;
    }
}

From source file:net.gbmb.collector.RecordController.java

@RequestMapping(value = "/records/{cid}/end", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public void endCollection(final @PathVariable("cid") String cid) throws CollectionStateException {
    Lock lock = hazelcast.getLock(cid);
    lock.lock();/*w  w  w .  j  a v  a  2s.  c om*/
    try {
        Collection collection = collectionMap.get(cid);
        if (collection == null) {
            // not existing collection
            throw new CollectionStateException("Collection not existing");
        } else if (collection.getState() == CollectionState.ENDED) {
            throw new CollectionStateException("Collection already ended");
        }
        // mark collection ended
        markCollectionEnded(collection);
    } finally {
        lock.unlock();
    }
    // post treatment on collection: push
    // done outside of lock
    pushQueue.offer(cid);
}

From source file:org.eclipse.gyrex.persistence.internal.storage.RepositoryRegistry.java

public void close(final String repositoryId) {
    if (!repositoryCache.containsKey(repositoryId)) {
        return;/*w  w w .  j ava  2s. c om*/
    }

    // lock
    final Lock lock = locksByRepositoryId.get(repositoryId);
    if (lock != null) {
        lock.lock();
    }
    final Repository repository;
    try {

        // remove cached instance
        repository = repositoryCache.remove(repositoryId);

        // remove from state map
        registryState.remove(STATE_REPOSITORY_PREFIX.concat(repositoryId));

        // remove lock
        locksByRepositoryId.remove(repositoryId);
    } finally {
        if (lock != null) {
            lock.unlock();
        }
    }

    // close repository outside lock
    if (null != repository) {
        try {
            repository.close();
        } catch (final Exception e) {
            LOG.error("Error closing repository {}. {}",
                    new Object[] { repositoryId, ExceptionUtils.getRootCauseMessage(e), e });
        }
    }

    // publish new state
    updateRepositoryState();
}

From source file:net.myrrix.online.ServerRecommender.java

private static float[] getFeatures(long id, FastByIDMap<float[]> matrix, ReadWriteLock lock) {
    float[] features;
    Lock readLock = lock.readLock();
    readLock.lock();/*  w ww .  j  a  va 2s  . c  o m*/
    try {
        features = matrix.get(id);
        if (features == null) {
            int numFeatures = countFeatures(matrix);
            if (numFeatures > 0) {
                features = new float[numFeatures];
                Lock writeLock = lock.writeLock();
                readLock.unlock();
                writeLock.lock();
                try {
                    matrix.put(id, features);
                } finally {
                    readLock.lock();
                    writeLock.unlock();
                }
            }
        }
    } finally {
        readLock.unlock();
    }
    return features;
}