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:org.pepstock.jem.node.JclCheckingQueueManager.java

/**
 * Loads all roles assigned to the user of job
 * @param user user of job //from w w  w  .  j a  v a  2  s  . c  o  m
 * @return list of roles of user
 * @throws NodeMessageException is any error occurs during getting the roles
 */
private List<Role> loadRoles(User user) throws NodeMessageException {
    // creates Hazelcast predicate to extract all roles and permissions
    // assigned to user
    RolesQueuePredicate predicate = new RolesQueuePredicate();
    predicate.setUser(user);

    // gets HC map for roles
    IMap<String, Role> roles = Main.getHazelcast().getMap(Queues.ROLES_MAP);
    // locks in HC to have a consistent status on roles
    Lock lock = Main.getHazelcast().getLock(Queues.ROLES_MAP_LOCK);
    List<Role> myroles = null;
    boolean isLock = false;
    try {
        // locks the map, if not EXCEPTION!!
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // reads the roles of the job user
            myroles = new ArrayList<Role>(roles.values(predicate));
        } else {
            throw new NodeMessageException(NodeMessage.JEMC119E, Queues.ROLES_MAP);
        }
    } catch (Exception e) {
        throw new NodeMessageException(NodeMessage.JEMC119E, e, Queues.ROLES_MAP);
    } finally {
        // always unlock 
        if (isLock) {
            lock.unlock();
        }
    }
    return myroles;
}

From source file:org.soaplab.services.storage.FileStorage.java

/**************************************************************************
 *
 **************************************************************************/
public void removeJob(String jobId) throws SoaplabException {

    // precaution: it is related to how the JobManager creates job
    // IDs (it is here intentionally in the not-too-portable way)
    if (!jobId.startsWith("[")) {
        log.warn("Trying to remove strangely named job: " + jobId);
        return;/*  ww w .  j a v a2 s.  c o  m*/
    }

    File jobDir = getJobDir(jobId);
    Lock writeLock = getLock(jobId, false);
    writeLock.lock();
    try {
        FileUtils.deleteDirectory(jobDir);
    } catch (IOException e) {
        throw new SoaplabException(
                "Error while deleting the job directory " + "of job " + jobId + ": " + e.toString());
    } finally {
        writeLock.unlock();
    }
}

From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java

/**
 * Initializes the cache. Only the cache specific to the sesison's locale
 * will be populated.//from w  w w .java2s .c om
 */
protected void initCache(IPentahoSession session) {

    final List<Catalog> cache = getCache(session);

    final boolean needUpdate;
    final Lock readLock = cacheLock.readLock();

    try {
        readLock.lock();
        // Check if the cache is empty.
        if (cache.size() == 0) {
            needUpdate = true;
        } else {
            needUpdate = false;
        }
    } finally {
        readLock.unlock();
    }

    if (needUpdate) {
        final Lock writeLock = cacheLock.writeLock();
        try {
            writeLock.lock();

            // First clear the cache
            cache.clear();

            final Callable<Void> call = new Callable<Void>() {
                public Void call() throws Exception {
                    // Now build the cache. Use the system session in the holder.
                    for (String name : getHelper().getHostedCatalogs()) {
                        try {
                            addCatalogToCache(PentahoSessionHolder.getSession(), name);
                        } catch (Throwable t) {
                            LOG.error("Failed to initialize the cache for OLAP connection " + name, t);
                        }
                    }
                    for (String name : getHelper().getOlap4jServers()) {
                        try {
                            addCatalogToCache(PentahoSessionHolder.getSession(), name);
                        } catch (Throwable t) {
                            LOG.error("Failed to initialize the cache for OLAP connection " + name, t);
                        }
                    }
                    return null;
                }
            };

            if (isSecurityEnabled()) {
                SecurityHelper.getInstance().runAsSystem(call);
            } else {
                call.call();
            }

            // Sort it all.
            Collections.sort(cache, new Comparator<IOlapService.Catalog>() {
                public int compare(Catalog o1, Catalog o2) {
                    return o1.name.compareTo(o2.name);
                }
            });

        } catch (Throwable t) {

            LOG.error("Failed to initialize the connection cache", t);

            throw new IOlapServiceException(t);

        } finally {
            writeLock.unlock();
        }
    }
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for setup a schema namespace (indexes)
 *
 * @param ns: namespace name//from  w w w . j av a  2s .  c  o m
 * @return 200 response
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/setup_schema")
public Response setupSchema(@PathParam("ns") String ns) {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        Application app = new Application(graphDB, ns);
        try (Transaction tx = graphDB.beginTx()) {
            app.setupSchema();
            tx.success();
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.OK).build();
}

From source file:org.apache.bookkeeper.bookie.EntryLogManagerForEntryLogPerLedger.java

public BufferedLogChannelWithDirInfo getCurrentLogWithDirInfoForLedger(long ledgerId) throws IOException {
    Lock lock = getLock(ledgerId);
    lock.lock();/*from  w w  w  .j ava 2  s.co m*/
    try {
        EntryLogAndLockTuple entryLogAndLockTuple = ledgerIdEntryLogMap.get(ledgerId);
        return entryLogAndLockTuple.getEntryLogWithDirInfo();
    } catch (Exception e) {
        log.error("Received unexpected exception while fetching entry from map for ledger: " + ledgerId, e);
        throw new IOException("Received unexpected exception while fetching entry from map", e);
    } finally {
        lock.unlock();
    }
}

From source file:org.paxml.control.MutexTag.java

/**
 * {@inheritDoc}//  w ww  .  j a  v  a 2 s  .  c  o  m
 */
@Override
protected Object doExecute(Context context) {
    String lockName = name == null ? null : name.evaluateString(context);
    if (lockName == null) {
        lockName = "";
    }
    Long timeoutValue = timeout == null ? null : ReflectUtils.coerceType(timeout.evaluate(context), Long.class);
    if (timeoutValue == null) {
        timeoutValue = DEFAULT_TIMEOUT;
    }
    Lock lock = getLock(lockName);

    if (log.isInfoEnabled()) {
        log.info("Waiting to enter mutex '" + lockName + "', timeout: " + timeoutValue);
    }
    long start = System.currentTimeMillis();
    long duration = 0;
    try {

        if (!lock.tryLock(timeoutValue, TimeUnit.MILLISECONDS)) {
            throw new PaxmlRuntimeException(
                    "Cannot enter mutex after waiting for " + timeoutValue + " ms, mutex name: " + lockName);
        }
        duration = System.currentTimeMillis() - start;
        start = System.currentTimeMillis();
        if (log.isInfoEnabled()) {

            log.info("Mutex '" + lockName + "' entered after waiting for " + duration + " ms");
        }
    } catch (InterruptedException e) {
        throw new PaxmlRuntimeException("Mutex entering interrupted, mutex name: " + lockName, e);
    }

    try {

        return super.doExecute(context);
    } finally {
        lock.unlock();
        if (log.isInfoEnabled()) {
            duration = System.currentTimeMillis() - start;
            log.info("Mutex '" + lockName + "' exited after being used for " + duration + " ms");
        }
    }

}

From source file:org.soaplab.services.storage.FileStorage.java

/**************************************************************************
 * Saves last event/*from  w  w w .j av a2s.  c  om*/
 **************************************************************************/
protected void setLastEvent(File jobDir, AnalysisEvent newEvent) {
    File lastEventFile = new File(jobDir, FILE_LAST_EVENT);
    Lock writelock = getLock(jobDir.getName(), false);
    writelock.lock();
    try {
        FileUtils.writeStringToFile(lastEventFile, newEvent.toString(), System.getProperty("file.encoding"));
    } catch (IOException e) {
        log.error("Cannot write to " + lastEventFile.getAbsolutePath() + ": " + e.toString());
    } finally {
        writelock.unlock();
    }
}

From source file:com.mastfrog.netty.http.client.CookieStore.java

void extract(HttpHeaders headers) {
    List<String> hdrs = headers.getAll(Headers.SET_COOKIE.name());
    if (!hdrs.isEmpty()) {
        Lock writeLock = lock.writeLock();
        try {/*from   w  w  w .  ja  va 2 s.c o m*/
            writeLock.lock();
            for (String header : hdrs) {
                try {
                    Cookie cookie = Headers.SET_COOKIE.toValue(header);
                    add(cookie);
                } catch (Exception e) {
                    if (errorHandler != null) {
                        errorHandler.receive(e);
                    } else {
                        Exceptions.chuck(e);
                    }
                }
            }
        } finally {
            writeLock.unlock();
        }
    }
}

From source file:org.soaplab.services.storage.FileStorage.java

/**************************************************************************
 * Returns currently saved last event (from the given 'jobDir').
 * May return null.//from www.  j a v  a2s  . com
 **************************************************************************/
protected AnalysisEvent getLastEvent(File jobDir) {
    if (deserializer != null) {
        File lastEventFile = new File(jobDir, FILE_LAST_EVENT);
        Lock readlock = getLock(jobDir.getName(), true);
        readlock.lock();
        try {
            if (lastEventFile.exists())
                return deserializer.deserialize(this, lastEventFile);
        } catch (Exception e) {
            log.error("Error by reading '" + lastEventFile + "': " + e.toString());
        } finally {
            readlock.unlock();
        }
    }
    return null;
}

From source file:com.alibaba.shared.django.DjangoClient.java

protected void refreshToken() throws URISyntaxException, IOException {
    Lock wl = lock.writeLock();
    wl.lock();/*from w w w.  j  ava  2  s .com*/
    try {
        final String timestamp = String.valueOf(new Date().getTime());
        DjangoMessage msg = executeRequest(new Supplier<HttpUriRequest>() {
            public HttpUriRequest get() {
                Map<String, String> params = Maps.newHashMap();
                params.put("appKey", appKey);
                params.put("timestamp", timestamp);
                params.put("signature", buildSignature(timestamp));
                return new HttpGet(buildURI(tokenUrl, params, false));
            }
        }, false);
        if (msg != null && msg.isSuccess()) {
            accessToken = msg.getString(ACCESS_TOKEN_KEY);
            LOGGER.info("Received accessToken {}", accessToken);
        }
    } finally {
        wl.unlock();
    }
}