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.threecrickets.prudence.cache.SqlCache.java

/**
 * Delete an entry.//from   w  w  w  .  ja  v a 2 s.  c om
 * 
 * @param connection
 *        The connection
 * @param key
 *        The key
 * @throws SQLException
 */
private void delete(Connection connection, String key) throws SQLException {
    Lock lock = lockSource.getWriteLock(key);
    lock.lock();
    try {
        String sql = "DELETE FROM " + cacheTableName + " WHERE key=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        try {
            statement.setString(1, key);
            if (!statement.execute()) {
                if (logger.isLoggable(Level.FINE) && statement.getUpdateCount() > 0)
                    logger.fine("Deleted: " + key);
            }
        } finally {
            statement.close();
        }
    } finally {
        lock.unlock();
        lockSource.discard(key);
    }
}

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

@Override
public SimpleFeatureCollection getGranules(Query q) throws IOException {
    Utilities.ensureNonNull("query", q);
    q = mergeHints(q);/*from w  ww .java2 s.c  o m*/
    String typeName = q.getTypeName();
    final Lock lock = rwLock.readLock();
    try {
        lock.lock();
        checkStore();

        //
        // Load tiles informations, especially the bounds, which will be
        // reused
        //
        final SimpleFeatureSource featureSource = tileIndexStore.getFeatureSource(typeName);
        if (featureSource == null) {
            throw new NullPointerException(
                    "The provided SimpleFeatureSource is null, it's impossible to create an index!");
        }
        return featureSource.getFeatures(q);

    } catch (Throwable e) {
        final IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    } finally {
        lock.unlock();

    }
}

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

@Override
public int removeGranules(Query query) {
    Utilities.ensureNonNull("query", query);
    query = mergeHints(query);//from   w  w  w  .java2 s  . c o m
    final Lock lock = rwLock.writeLock();
    try {
        lock.lock();
        // check if the index has been cleared
        checkStore();
        String typeName = query.getTypeName();
        SimpleFeatureStore fs = null;
        try {
            // create a writer that appends this features
            fs = (SimpleFeatureStore) tileIndexStore.getFeatureSource(typeName);
            final int retVal = fs.getCount(query);
            fs.removeFeatures(query.getFilter());

            // update bounds
            bounds.put(typeName, tileIndexStore.getFeatureSource(typeName).getBounds());

            return retVal;

        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
            return -1;
        }
        // do your thing
    } finally {
        lock.unlock();

    }
}

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

@Override
public int getGranulesCount(Query q) throws IOException {
    Utilities.ensureNonNull("query", q);
    q = mergeHints(q);/* w w  w . j  a  va 2  s . com*/
    String typeName = q.getTypeName();
    final Lock lock = rwLock.readLock();
    try {
        lock.lock();
        checkStore();

        //
        // Load tiles informations, especially the bounds, which will be
        // reused
        //
        final SimpleFeatureSource featureSource = tileIndexStore.getFeatureSource(typeName);
        if (featureSource == null) {
            throw new NullPointerException(
                    "The provided SimpleFeatureSource is null, it's impossible to create an index!");
        }
        int count = featureSource.getCount(q);
        if (count == -1) {
            return featureSource.getFeatures(q).size();
        }
        return count;

    } catch (Throwable e) {
        final IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    } finally {
        lock.unlock();

    }
}

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

@Override
public void addGranules(final String typeName, final Collection<SimpleFeature> granules,
        final Transaction transaction) throws IOException {
    Utilities.ensureNonNull("granuleMetadata", granules);
    final Lock lock = rwLock.writeLock();
    try {//from w w w  .j  av  a2 s .c o m
        lock.lock();
        // check if the index has been cleared
        checkStore();

        SimpleFeatureStore store = (SimpleFeatureStore) tileIndexStore.getFeatureSource(typeName);
        store.setTransaction(transaction);

        ListFeatureCollection featureCollection = new ListFeatureCollection(tileIndexStore.getSchema(typeName));

        // add them all
        Set<FeatureId> fids = new HashSet<FeatureId>();
        for (SimpleFeature f : granules) {
            // Add the feature to the feature collection
            featureCollection.add(f);
            fids.add(ff.featureId(f.getID()));
        }
        store.addFeatures(featureCollection);

        // update bounds
        if (bounds.containsKey(typeName)) {
            bounds.remove(typeName);
        }

    } finally {
        lock.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 av  a 2s.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:gridool.db.sql.ParallelSQLMapTask.java

@Override
protected ParallelSQLMapTaskResult execute() throws GridException {
    assert (registry != null);

    final File tmpFile;
    try {/*w ww  .jav  a 2 s  .  co  m*/
        tmpFile = File.createTempFile("PSQLMap" + taskNumber + '_', '_' + NetUtils.getLocalHostAddress());
    } catch (IOException e) {
        throw new GridException(e);
    }

    final QueryString[] queries = SQLTranslator.divideQuery(query, true);
    final boolean singleStatement = (queries.length == 1);
    final String selectQuery = singleStatement ? query : SQLTranslator.selectFirstSelectQuery(queries);

    GridNode localNode = config.getLocalNode();
    GridNode senderNode = getSenderNode();
    assert (senderNode != null);
    final boolean useCreateTableAS = senderNode.equals(localNode);

    final int fetchedRows;
    final LockManager lockMgr = registry.getLockManager();
    final ReadWriteLock rwlock = lockMgr.obtainLock(DBAccessor.SYS_TABLE_SYMBOL);
    final Lock lock = rwlock.writeLock(); // REVIEWME tips: exclusive lock for system table in MonetDB
    long startQueryTime = System.currentTimeMillis();
    final Connection dbConn = getDbConnection(taskMasterNode, registry);
    try {
        lock.lock();
        if (singleStatement) {
            // #1 invoke COPY INTO file
            if (useCreateTableAS) {
                dbConn.setAutoCommit(true);
                fetchedRows = executeCreateTableAs(dbConn, selectQuery, taskTableName);
            } else {
                dbConn.setAutoCommit(false);
                fetchedRows = executeCopyIntoFile(dbConn, selectQuery, taskTableName, tmpFile);
                dbConn.commit();
            }
        } else {
            dbConn.setAutoCommit(false);
            // #1-1 DDL before map SELECT queries (e.g., create view)
            issueDDLBeforeSelect(dbConn, queries);
            // #1-2 invoke COPY INTO file
            if (useCreateTableAS) {
                fetchedRows = executeCreateTableAs(dbConn, selectQuery, taskTableName);
            } else {
                fetchedRows = executeCopyIntoFile(dbConn, selectQuery, taskTableName, tmpFile);
            }
            // #1-3 DDL after map SELECT queries (e.g., drop view)
            issueDDLAfterSelect(dbConn, queries);
            dbConn.commit();
        }
        assert (fetchedRows != -1);
    } catch (SQLException sqle) {
        String errmsg = "Failed to execute a query: \n" + query;
        LOG.error(errmsg, sqle);
        if (singleStatement) {
            try {
                dbConn.rollback();
            } catch (SQLException rbe) {
                LOG.warn("Rollback failed", rbe);
            }
        }
        new FileDeletionThread(tmpFile, LOG).start();
        throw new GridException(errmsg, sqle);
    } catch (Throwable e) {
        String errmsg = "Failed to execute a query: \n" + query;
        LOG.fatal(errmsg, e);
        if (singleStatement) {
            try {
                dbConn.rollback();
            } catch (SQLException rbe) {
                LOG.warn("Rollback failed", rbe);
            }
        }
        new FileDeletionThread(tmpFile, LOG).start();
        throw new GridException(errmsg, e);
    } finally {
        lock.unlock();
        JDBCUtils.closeQuietly(dbConn);
    }
    long queryExecTime = System.currentTimeMillis() - startQueryTime;

    String sentFileName = null;
    long sendResultTime = -1L; // would be null for a local task
    if (fetchedRows > 0) {
        // #2 send file
        long startResultTime = System.currentTimeMillis();
        try {
            TransferUtils.sendfile(tmpFile, dstAddr, dstPort, false, true);
            sendResultTime = System.currentTimeMillis() - startResultTime;
            sentFileName = tmpFile.getName();
        } catch (IOException e) {
            throw new GridException("failed to sending a file", e);
        } finally {
            new FileDeletionThread(tmpFile, LOG).start();
        }
    }
    return new ParallelSQLMapTaskResult(taskMasterNode, sentFileName, taskNumber, fetchedRows, queryExecTime,
            sendResultTime);
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

public void invalidate(String tag) {
    try {//from   ww  w .j  a  va2s .com
        Connection connection = connect();
        if (connection == null)
            return;

        try {
            List<String> tagged = getTagged(connection, tag);
            if (tagged.isEmpty())
                return;

            ArrayList<Lock> locks = new ArrayList<Lock>(tagged.size());

            String sql = "DELETE FROM " + cacheTableName + " WHERE key IN (";
            for (String key : tagged) {
                sql += "?,";
                locks.add(lockSource.getWriteLock(key));
            }
            sql = sql.substring(0, sql.length() - 1) + ")";

            for (Lock lock : locks)
                lock.lock();
            try {
                PreparedStatement statement = connection.prepareStatement(sql);
                try {
                    int i = 1;
                    for (String key : tagged)
                        statement.setString(i++, key);
                    if (!statement.execute())
                        logger.fine("Invalidated " + statement.getUpdateCount());
                } finally {
                    statement.close();
                }

                for (String key : tagged)
                    lockSource.discard(key);
            } finally {
                for (Lock lock : locks)
                    lock.unlock();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException x) {
        logger.log(Level.WARNING, "Could not invalidate cache tag", x);
    }
}

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

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onError(Exception)}.</p>
 *  /*from   w  w w.j a v a  2  s .co m*/
 * @since 1.3.0
 */
@Test
public final void testAsyncError() throws InterruptedException {

    String subpath = "/asyncerror", body = "non-JSON-content";

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

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

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

    asyncEndpoint.asyncError(new AsyncHandler<User>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, User user) {
        }

        @Override
        public void onError(InvocationException error) {

            lock.lock();

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

            lock.unlock();
        }
    });

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

    verify(getRequestedFor(urlEqualTo(subpath)));

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

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

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onFailure(HttpResponse)}.</p>
 *  /*from   ww  w .ja v a2  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);
}