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:jp.aegif.nemaki.cmis.service.impl.VersioningServiceImpl.java

@Override
public ObjectData getObjectOfLatestVersion(CallContext context, String repositoryId, String objectId,
        String versionSeriesId, Boolean major, String filter, Boolean includeAllowableActions,
        IncludeRelationships includeRelationships, String renditionFilter, Boolean includePolicyIds,
        Boolean includeAcl, ExtensionsData extension) {
    // //////////////////
    // General Exception
    // //////////////////
    // Chemistry Atompub calls this method only with objectId
    if (versionSeriesId == null) {
        exceptionService.invalidArgumentRequiredString("objectId", objectId);
        Document d = contentService.getDocument(repositoryId, objectId);
        versionSeriesId = d.getVersionSeriesId();
    }//from w ww  .j  av  a  2  s .  c  o m

    // Default to false
    Boolean _major = (major == null) ? false : major;
    Document document = null;
    if (_major) {
        document = contentService.getDocumentOfLatestMajorVersion(repositoryId, versionSeriesId);
    } else {
        document = contentService.getDocumentOfLatestVersion(repositoryId, versionSeriesId);
    }

    Lock lock = threadLockService.getReadLock(repositoryId, document.getId());

    try {
        lock.lock();

        exceptionService.objectNotFound(DomainType.OBJECT, document, versionSeriesId);
        exceptionService.permissionDenied(context, repositoryId, PermissionMapping.CAN_GET_PROPERTIES_OBJECT,
                document);

        // //////////////////
        // Body of the method
        // //////////////////
        ObjectData objectData = compileService.compileObjectData(context, repositoryId, document, filter,
                includeAllowableActions, includeRelationships, renditionFilter, includeAcl);
        return objectData;

    } finally {
        lock.unlock();
    }
}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

@Override
public QueryCapabilities getQueryCapabilities(String typeName) {
    final Lock lock = rwLock.readLock();
    try {/*from   w w w  .  java2 s  .  c o m*/
        lock.lock();
        checkStore();
        return tileIndexStore.getFeatureSource(typeName).getQueryCapabilities();
    } catch (IOException e) {
        if (LOGGER.isLoggable(Level.INFO))
            LOGGER.log(Level.INFO, "Unable to collect QueryCapabilities", e);
        return null;
    } finally {
        lock.unlock();
    }
}

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

@Override
public boolean commitEntryMemTableFlush() throws IOException {
    // lock it only if there is new data
    // so that cache accesstime is not changed
    Set<BufferedLogChannelWithDirInfo> copyOfCurrentLogsWithDirInfo = getCopyOfCurrentLogs();
    for (BufferedLogChannelWithDirInfo currentLogWithDirInfo : copyOfCurrentLogsWithDirInfo) {
        BufferedLogChannel currentLog = currentLogWithDirInfo.getLogChannel();
        if (reachEntryLogLimit(currentLog, 0L)) {
            Long ledgerId = currentLog.getLedgerIdAssigned();
            Lock lock = getLock(ledgerId);
            lock.lock();//from w ww .  jav  a2 s  . c  o m
            try {
                if (reachEntryLogLimit(currentLog, 0L)) {
                    log.info("Rolling entry logger since it reached size limitation for ledger: {}", ledgerId);
                    createNewLog(ledgerId, "after entry log file is rotated");
                }
            } finally {
                lock.unlock();
            }
        }
    }
    /*
     * in the case of entrylogperledger, SyncThread drives
     * checkpoint logic for every flushInterval. So
     * EntryMemtable doesn't need to call checkpoint in the case
     * of entrylogperledger.
     */
    return false;
}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

public void createType(SimpleFeatureType featureType) throws IOException {
    Utilities.ensureNonNull("featureType", featureType);
    final Lock lock = rwLock.writeLock();
    String typeName = null;//from  w ww. ja  v  a  2 s  .c  o m
    try {
        lock.lock();
        checkStore();

        tileIndexStore.createSchema(featureType);
        typeName = featureType.getTypeName();
        if (typeName != null) {
            addTypeName(typeName, true);
        }
        extractBasicProperties(typeName);
    } finally {
        lock.unlock();
    }

}

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

private void createNewIndexerTask(final ServerBaseEntry entry, final IndexAction action) {
    checkDestroyed();//  w ww  .  j a  v  a2 s. c o m
    checkInitialized();
    String serviceName = entry.getServiceConfig().getName();
    if (LOG.isInfoEnabled())
        LOG.info("New Indexer Task submitted - Action: " + action + " for service: " + serviceName);
    ServiceIndex bean = this.indexerMap.get(serviceName);
    if (bean == null)
        throw new RuntimeException("no indexer for service " + serviceName + " registered");
    /*
     * lock on service to synchronize the event order. This lock has
     * fairness parameter set to true. Grant access to the longest waiting
     * thread. Using fairness is slower but is acceptable in this context
     */
    Lock lock = bean.getLock();
    lock.lock();
    try {
        IndexSchema schema = bean.getSchema();
        boolean commitAfter = bean.incrementActionAndReset(schema.getCommitAfterDocuments());
        IndexDocumentBuilder<IndexDocument> callable = new IndexDocumentBuilderTask<IndexDocument>(entry,
                bean.getSchema(), action, commitAfter, bean.getOptimize(schema.getOptimizeAfterCommit()));
        sumbitTask(callable, bean.getIndexer());
    } finally {
        /*
         * make sure to unlock
         */
        lock.unlock();
    }

}

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

void doFlushHierarchy(final IPath contextPath) {
    // log debug message
    if (ContextDebug.debug) {
        LOG.debug("Flushing context hierarchy {}...", contextPath);
    }/*from  ww  w.  jav  a 2 s .  c  om*/

    // remove all entries within that path
    final List<GyrexContextImpl> removedContexts = new ArrayList<GyrexContextImpl>();
    final Lock lock = contextRegistryLock.writeLock();
    lock.lock();
    try {
        checkClosed();
        final Entry[] entrySet = contexts.entrySet().toArray(new Entry[0]);
        for (final Entry entry : entrySet) {
            final IPath entryPath = (IPath) entry.getKey();
            if (contextPath.isPrefixOf(entryPath)) {
                final GyrexContextImpl contextImpl = contexts.remove(entryPath);
                if (null != contextImpl) {
                    removedContexts.add(contextImpl);
                }
            }
        }
    } finally {
        lock.unlock();
    }

    // dispose all removed contexts (outside of lock)
    for (final GyrexContextImpl contextImpl : removedContexts) {
        if (ContextDebug.debug) {
            LOG.debug("Disposing context {}...", contextImpl);
        }
        contextImpl.dispose();
    }

    // log info message
    LOG.info("Flushed context hierarchy {}.", contextPath);
}

From source file:com.ignorelist.kassandra.steam.scraper.FileCache.java

@Override
public InputStream get(String key, Callable<? extends InputStream> valueLoader) throws ExecutionException {
    InputStream inputStream = getIfPresent(key);
    if (null != inputStream) {
        return inputStream;
    }/*from   ww w.j  a v  a  2 s . c  o  m*/
    final Lock writeLock = stripedLock.get(key).writeLock();
    writeLock.lock();
    try {
        inputStream = getIfPresentNonBlocking(key);
        if (null != inputStream) {
            return inputStream;
        }
        try {
            inputStream = valueLoader.call();
            try {
                putNonBlocking(key, inputStream);
                return getIfPresentNonBlocking(key);
            } catch (IOException ex) {
                Logger.getLogger(FileCache.class.getName()).log(Level.SEVERE, "failed to write cache file", ex);
                throw new ExecutionException("failed to load " + key, ex);
            }
        } catch (Exception e) {
            Logger.getLogger(FileCache.class.getName()).log(Level.SEVERE, null, e);
            throw new ExecutionException(e);
        }
    } finally {
        writeLock.unlock();
    }

}

From source file:io.fabric8.maven.core.service.PortForwardService.java

/**
 * Forwards a port to the newest pod matching the given selector.
 * If another pod is created, it forwards connections to the new pod once it's ready.
 *///from w  ww. j a v a  2 s .  c o m
public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector,
        final int remotePort, final int localPort) throws Fabric8ServiceException {

    final Lock monitor = new ReentrantLock(true);
    final Condition podChanged = monitor.newCondition();
    final Pod[] nextForwardedPod = new Pod[1];

    final Thread forwarderThread = new Thread() {
        @Override
        public void run() {

            Pod currentPod = null;
            Closeable currentPortForward = null;

            try {
                monitor.lock();

                while (true) {
                    if (podEquals(currentPod, nextForwardedPod[0])) {
                        podChanged.await();
                    } else {
                        Pod nextPod = nextForwardedPod[0]; // may be null
                        try {
                            monitor.unlock();
                            // out of critical section

                            if (currentPortForward != null) {
                                log.info("Closing port-forward from pod %s",
                                        KubernetesHelper.getName(currentPod));
                                currentPortForward.close();
                                currentPortForward = null;
                            }

                            if (nextPod != null) {
                                log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
                                currentPortForward = forwardPortAsync(externalProcessLogger,
                                        KubernetesHelper.getName(nextPod), remotePort, localPort);
                            } else {
                                log.info("Waiting for a pod to become ready before starting port-forward");
                            }
                            currentPod = nextPod;
                        } finally {
                            monitor.lock();
                        }
                    }

                }

            } catch (InterruptedException e) {
                log.debug("Port-forwarding thread interrupted", e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                log.warn("Error while port-forwarding to pod", e);
            } finally {
                monitor.unlock();

                if (currentPortForward != null) {
                    try {
                        currentPortForward.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    // Switching forward to the current pod if present
    Pod newPod = getNewestPod(podSelector);
    nextForwardedPod[0] = newPod;

    final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), podSelector, log)
            .watch(new Watcher<Pod>() {

                @Override
                public void eventReceived(Action action, Pod pod) {
                    monitor.lock();
                    try {
                        List<Pod> candidatePods;
                        if (nextForwardedPod[0] != null) {
                            candidatePods = new LinkedList<>();
                            candidatePods.add(nextForwardedPod[0]);
                            candidatePods.add(pod);
                        } else {
                            candidatePods = Collections.singletonList(pod);
                        }
                        Pod newPod = getNewestPod(candidatePods); // may be null
                        if (!podEquals(nextForwardedPod[0], newPod)) {
                            nextForwardedPod[0] = newPod;
                            podChanged.signal();
                        }
                    } finally {
                        monitor.unlock();
                    }
                }

                @Override
                public void onClose(KubernetesClientException e) {
                    // don't care
                }
            });

    forwarderThread.start();

    final Closeable handle = new Closeable() {
        @Override
        public void close() throws IOException {
            try {
                watch.close();
            } catch (Exception e) {
            }
            try {
                forwarderThread.interrupt();
                forwarderThread.join(15000);
            } catch (Exception e) {
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                handle.close();
            } catch (Exception e) {
                // suppress
            }
        }
    });

    return handle;
}

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

public void flushAll(IPentahoSession session) {
    final Lock writeLock = cacheLock.writeLock();
    try {/*ww  w.j a v a 2 s  .  co m*/
        writeLock.lock();

        // Start by flushing the local cache.
        resetCache(session);

        flushHostedAndRemote(session);
    } catch (Exception e) {
        throw new IOlapServiceException(e);
    } finally {
        writeLock.unlock();
    }
}

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

public void add(Cookie cookie) {
    String name = cookie.getName();
    Lock writeLock = lock.writeLock();
    try {/* w w  w .  j  a  v  a2  s.  c o  m*/
        writeLock.lock();
        for (Iterator<DateCookie> it = cookies.iterator(); it.hasNext();) {
            DateCookie ck = it.next();
            if (name.equals(ck.getName())) {
                it.remove();
            } else if (ck.isExpired()) {
                it.remove();
            }
        }
        if (!cookie.isDiscard() && cookie.getMaxAge() > 0) {
            cookies.add(new DateCookie(cookie));
        }
    } finally {
        writeLock.unlock();
    }
}