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.netxforge.oss2.config.DatabaseSchemaConfigFactory.java

/**
 * Return the database schema./*w  w  w.j a v  a2  s.co  m*/
 *
 * @return the database schema
 */
public DatabaseSchema getDatabaseSchema() {
    final Lock lock = getReadLock();
    lock.lock();
    try {
        return m_config;
    } finally {
        lock.unlock();
    }
}

From source file:com.netxforge.oss2.config.DatabaseSchemaConfigFactory.java

/**
 * Return a count of the number of tables defined.
 *
 * @return the number of tables in the schema
 *//* ww  w  .  j  a  v  a2s  .c  o  m*/
public int getTableCount() {
    final Lock lock = getReadLock();
    lock.lock();
    try {
        return getDatabaseSchema().getTableCount();
    } finally {
        lock.unlock();
    }
}

From source file:com.enonic.cms.core.portal.image.ImageServiceImpl.java

public ImageResponse process(ImageRequest imageRequest) {
    Preconditions.checkNotNull(imageRequest, "imageRequest cannot be null");

    final ImageRequestTrace imageRequestTrace = livePortalTraceService.getCurrentTrace().getImageRequestTrace();

    String blobKey = getBlobKey(imageRequest);
    if (blobKey == null) {
        return ImageResponse.notFound();
    }/*  w  w w .j a  va2s. c  o m*/

    imageRequest.setBlobKey(blobKey);

    final Lock locker = concurrencyLock.getLock(imageRequest.getCacheKey());
    try {
        ImageRequestTracer.startConcurrencyBlockTimer(imageRequestTrace);
        locker.lock();
        ImageRequestTracer.stopConcurrencyBlockTimer(imageRequestTrace);

        ImageResponse res = imageCache.get(imageRequest);
        if (res != null) {
            ImageRequestTracer.traceImageResponse(imageRequestTrace, res);
            ImageRequestTracer.traceUsedCachedResult(imageRequestTrace, true);
            return res;
        }

        try {
            res = doProcess(imageRequest);
            ImageRequestTracer.traceImageResponse(imageRequestTrace, res);
            ImageRequestTracer.traceUsedCachedResult(imageRequestTrace, false);
            return res;
        } catch (AttachmentNotFoundException e) {
            LOG.error(
                    "Cannot read image with key {} from configured BLOB directory ( {} ). Check your CMS configuration.",
                    blobKey, directory.getAbsolutePath());
            return ImageResponse.notFound();
        } catch (Exception e) {
            throw new ImageProcessorException("Failed to process image [contentKey="
                    + imageRequest.getContentKey() + "] : " + e.getMessage(), e);
        }
    } finally {
        locker.unlock();
    }
}

From source file:jenkins.plugins.git.GitSCMFileSystem.java

@Override
public boolean changesSince(@CheckForNull SCMRevision revision, @NonNull OutputStream changeLogStream)
        throws UnsupportedOperationException, IOException, InterruptedException {
    AbstractGitSCMSource.SCMRevisionImpl rev = getRevision();
    if (rev == null ? revision == null : rev.equals(revision)) {
        // special case where somebody is asking one of two stupid questions:
        // 1. what has changed between the latest and the latest
        // 2. what has changed between the current revision and the current revision
        return false;
    }//from  ww w.  java 2  s  .  c  o m
    Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry);
        if (cacheDir == null || !cacheDir.isDirectory()) {
            throw new IOException("Closed");
        }
        boolean executed = false;
        ChangelogCommand changelog = client.changelog();
        try (Writer out = new OutputStreamWriter(changeLogStream, "UTF-8")) {
            changelog.includes(commitId);
            ObjectId fromCommitId;
            if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
                fromCommitId = ObjectId.fromString(((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash());
                changelog.excludes(fromCommitId);
            } else {
                fromCommitId = null;
            }
            changelog.to(out).max(GitSCM.MAX_CHANGELOG).execute();
            executed = true;
            return !commitId.equals(fromCommitId);
        } catch (GitException ge) {
            throw new IOException("Unable to retrieve changes", ge);
        } finally {
            if (!executed) {
                changelog.abort();
            }
            changeLogStream.close();
        }
    } finally {
        cacheLock.unlock();
    }
}

From source file:com.gooddata.http.client.GoodDataHttpClient.java

private HttpResponse handleResponse(final HttpHost httpHost, final HttpRequest request,
        final HttpResponse originalResponse, final HttpContext context) throws IOException {
    final GoodDataChallengeType challenge = identifyGoodDataChallenge(originalResponse);
    if (challenge == GoodDataChallengeType.UNKNOWN) {
        return originalResponse;
    }/*from ww  w.j  a  v a2 s  . co m*/
    EntityUtils.consume(originalResponse.getEntity());

    try {
        if (authLock.tryLock()) {
            //only one thread requiring authentication will get here.
            final Lock writeLock = rwLock.writeLock();
            writeLock.lock();
            boolean doSST = true;
            try {
                if (challenge == GoodDataChallengeType.TT && sst != null) {
                    if (refreshTt()) {
                        doSST = false;
                    }
                }
                if (doSST) {
                    sst = sstStrategy.obtainSst(httpClient, authHost);
                    if (!refreshTt()) {
                        throw new GoodDataAuthException("Unable to obtain TT after successfully obtained SST");
                    }
                }
            } catch (GoodDataAuthException e) {
                return new BasicHttpResponse(new BasicStatusLine(originalResponse.getProtocolVersion(),
                        HttpStatus.SC_UNAUTHORIZED, e.getMessage()));
            } finally {
                writeLock.unlock();
            }
        } else {
            // the other thread is performing auth and thus is holding the write lock
            // lets wait until it is finished (the write lock is granted) and then continue
            authLock.lock();
        }
    } finally {
        authLock.unlock();
    }
    return this.execute(httpHost, request, context);
}

From source file:gridool.db.partitioning.phihash.monetdb.MonetDBCsvLoadOperation.java

@Override
public Long execute() throws SQLException, GridException {
    if (expectedNumRecords == -1L) {
        throw new IllegalStateException();
    }/* w w  w . j  a  v  a  2s.  c  o m*/
    // clear index buffer
    final ILocalDirectory index = registry.getDirectory();
    try {
        index.purgeAll(true);
        index.setBulkloading(false);
    } catch (IndexException dbe) {
        LOG.error(dbe);
    }
    InMemoryMappingIndex mmidx = registry.getMappingIndex();
    mmidx.saveIndex(true, false);

    LockManager lockMgr = registry.getLockManager();
    //String dbid = getConnectionUrl();
    //ReadWriteLock systblLock = lockMgr.obtainLock(dbid);
    // [Design notes] Better performance can be expected for a single bulkload process than multiple one.
    ReadWriteLock systblLock = lockMgr.obtainLock(DBAccessor.SYS_TABLE_SYMBOL);

    long actualInserted = 0L;
    final Lock exlock = systblLock.writeLock();
    exlock.lock();
    final Connection conn = getConnection();
    final String dburl = getConnectionUrl();
    try {
        // #1 create table
        prepareTable(conn, createTableDDL, tableName);
        // #2 invoke COPY INTO
        final StopWatch sw = new StopWatch();
        if (expectedNumRecords > 0L) {
            if (ENV_MONETDB_USE_NOV09_OPT) {
                JDBCUtils.update(conn, "SET optimizer='nov2009_pipe'");
                actualInserted = invokeCopyInto(conn, copyIntoQuery, tableName, csvFileName,
                        expectedNumRecords);
                JDBCUtils.update(conn, "SET optimizer='default_pipe'");
            } else {
                actualInserted = invokeCopyInto(conn, copyIntoQuery, tableName, csvFileName,
                        expectedNumRecords);
            }
            if (actualInserted != expectedNumRecords) {
                String errmsg = "Expected records (" + expectedNumRecords + ") != Actual records ("
                        + actualInserted + "): \n" + getCopyIntoQuery(copyIntoQuery, expectedNumRecords);
                LOG.error(errmsg);
                throw new GridException(errmsg);
            }
            LOG.info("Elapsed time for COPY " + actualInserted + " RECORDS INTO " + tableName + " [" + dburl
                    + "]: " + sw.toString());
        }
        // #3 create indices and constraints
        if (alterTableDDL != null) {
            sw.start();
            alterTable(conn, alterTableDDL);
            LOG.info("Elapsed time for creating indices and constraints on table '" + tableName + "': "
                    + sw.toString());
        }
    } finally {
        JDBCUtils.closeQuietly(conn);
        if (ENV_RESTART_AFTER_COPYINTO && actualInserted > ENV_COPYINTO_PIECES) {
            if (MonetDBUtils.restartLocalDbInstance(dburl)) {
                if (ENV_SLEEP_AFTER_RESTART > 0L) {
                    try {
                        Thread.sleep(ENV_SLEEP_AFTER_RESTART);
                    } catch (InterruptedException e) {
                        ;
                    }
                }
            } else {
                LOG.warn("failed to restart MonetDB instance: " + dburl);
            }
        }
        exlock.unlock();
    }
    return actualInserted;
}

From source file:jp.aegif.nemaki.cmis.service.impl.AclServiceImpl.java

@Override
public Acl getAcl(CallContext callContext, String repositoryId, String objectId, Boolean onlyBasicPermissions) {

    exceptionService.invalidArgumentRequired("objectId", objectId);

    Lock lock = threadLockService.getReadLock(repositoryId, objectId);

    try {//from ww w.java2s  .c  o  m
        lock.lock();

        // //////////////////
        // General Exception
        // //////////////////

        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_GET_ACL_OBJECT,
                content);

        // //////////////////
        // Body of the method
        // //////////////////
        jp.aegif.nemaki.model.Acl acl = contentService.calculateAcl(repositoryId, content);
        //return compileService.compileAcl(acl, content.isAclInherited(), onlyBasicPermissions);
        return compileService.compileAcl(acl, contentService.getAclInheritedWithDefault(repositoryId, content),
                onlyBasicPermissions);
    } finally {
        lock.unlock();
    }
}

From source file:org.mule.modules.jmsbatchmessaging.JmsBatchMessagingConnector.java

/**
 * Consume messages in batches from a JMS destination.
 * <p/>//from w  ww .j  a v a2  s  .c  om
 * {@sample.xml ../../../doc/jms-batch-messaging-connector.xml.sample
 * jms-batch-messaging:consume}
 *
 * @param destinationName The JMS destination to consume messages from
 * @param amountOfThreads The amount of threads used to consume messages in parallel batches
 * @param batchSize       The size of each batch
 * @param timeout         The timeout, in milliseconds, to wait before releasing a batch that hasn't received its full batch of messages
 * @param isTopic         Whether or not the JMS destination is a topic.
 * @throws Exception
 */
@Source
public void consume(String destinationName, int amountOfThreads, Boolean isTopic, int batchSize, long timeout,
        final SourceCallback callback) throws Exception {
    Lock lock = null;

    try {
        lock = muleContext.getLockFactory().createLock("JMS_BATCH_MESSAGING_CONSUMER_LOCK");
        lock.lock();

        logger.debug(String.format("Starting batch (size=%s) processing with %s threads", batchSize,
                amountOfThreads));

        ExecutorService executorService = Executors.newFixedThreadPool(amountOfThreads);
        for (int i = 0; i < amountOfThreads; i++) {
            executorService.execute(new DestinationMessageConsumer(muleContext, batchSize, timeout, callback,
                    connector, destinationName, isTopic, isTransactional));
        }

        executorService.shutdown();

        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            logger.debug("Thread interrupted");
        }

    } finally {
        if (lock != null) {
            lock.unlock();
        }
    }
}

From source file:at.newmedialab.ldclient.service.LDCache.java

private void lockResource(URI resource) {
    Lock lock;
    synchronized (resourceLocks) {
        lock = resourceLocks.get(resource);
        if (lock == null) {
            lock = new ReentrantLock();
            resourceLocks.put(resource, lock);
        }//from w  w  w .j a  v a  2  s  .  c  o m
    }
    lock.lock();
}

From source file:com.gooddata.http.client.GoodDataHttpClient.java

@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
    notNull(request, "Request can't be null");

    final boolean logoutRequest = isLogoutRequest(target, request);
    final Lock lock = logoutRequest ? rwLock.writeLock() : rwLock.readLock();

    lock.lock();

    final HttpResponse resp;
    try {// w  w w.ja  va  2 s  .c o m
        if (tt != null) {
            // this adds TT header to EVERY request to ALL hosts made by this HTTP client
            // however the server performs additional checks to ensure client is not using forged TT
            request.setHeader(TT_HEADER, tt);

            if (logoutRequest) {
                try {
                    sstStrategy.logout(httpClient, target, request.getRequestLine().getUri(), sst, tt);
                    tt = null;
                    sst = null;

                    return new BasicHttpResponse(new BasicStatusLine(request.getProtocolVersion(),
                            HttpStatus.SC_NO_CONTENT, "Logout successful"));
                } catch (GoodDataLogoutException e) {
                    return new BasicHttpResponse(new BasicStatusLine(request.getProtocolVersion(),
                            e.getStatusCode(), e.getStatusText()));
                }
            }
        }
        resp = this.httpClient.execute(target, request, context);
    } finally {
        lock.unlock();
    }
    return handleResponse(target, request, resp, context);
}